babylon.max.js 3.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602
  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, mimeType) {
  4924. if (mimeType === void 0) { mimeType = "image/png"; }
  4925. // Read the contents of the framebuffer
  4926. var numberOfChannelsByLine = width * 4;
  4927. var halfHeight = height / 2;
  4928. //Reading datas from WebGL
  4929. var data = engine.readPixels(0, 0, width, height);
  4930. //To flip image on Y axis.
  4931. for (var i = 0; i < halfHeight; i++) {
  4932. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4933. var currentCell = j + i * numberOfChannelsByLine;
  4934. var targetLine = height - i - 1;
  4935. var targetCell = j + targetLine * numberOfChannelsByLine;
  4936. var temp = data[currentCell];
  4937. data[currentCell] = data[targetCell];
  4938. data[targetCell] = temp;
  4939. }
  4940. }
  4941. // Create a 2D canvas to store the result
  4942. if (!screenshotCanvas) {
  4943. screenshotCanvas = document.createElement('canvas');
  4944. }
  4945. screenshotCanvas.width = width;
  4946. screenshotCanvas.height = height;
  4947. var context = screenshotCanvas.getContext('2d');
  4948. // Copy the pixels to a 2D canvas
  4949. var imageData = context.createImageData(width, height);
  4950. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4951. var castData = imageData.data;
  4952. castData.set(data);
  4953. context.putImageData(imageData, 0, 0);
  4954. var base64Image = screenshotCanvas.toDataURL(mimeType);
  4955. if (successCallback) {
  4956. successCallback(base64Image);
  4957. }
  4958. else {
  4959. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4960. if (("download" in document.createElement("a"))) {
  4961. var a = window.document.createElement("a");
  4962. a.href = base64Image;
  4963. var date = new Date();
  4964. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4965. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4966. window.document.body.appendChild(a);
  4967. a.addEventListener("click", function () {
  4968. a.parentElement.removeChild(a);
  4969. });
  4970. a.click();
  4971. }
  4972. else {
  4973. var newWindow = window.open("");
  4974. var img = newWindow.document.createElement("img");
  4975. img.src = base64Image;
  4976. newWindow.document.body.appendChild(img);
  4977. }
  4978. }
  4979. };
  4980. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  4981. if (mimeType === void 0) { mimeType = "image/png"; }
  4982. var width;
  4983. var height;
  4984. //If a precision value is specified
  4985. if (size.precision) {
  4986. width = Math.round(engine.getRenderWidth() * size.precision);
  4987. height = Math.round(width / engine.getAspectRatio(camera));
  4988. size = { width: width, height: height };
  4989. }
  4990. else if (size.width && size.height) {
  4991. width = size.width;
  4992. height = size.height;
  4993. }
  4994. else if (size.width && !size.height) {
  4995. width = size.width;
  4996. height = Math.round(width / engine.getAspectRatio(camera));
  4997. size = { width: width, height: height };
  4998. }
  4999. else if (size.height && !size.width) {
  5000. height = size.height;
  5001. width = Math.round(height * engine.getAspectRatio(camera));
  5002. size = { width: width, height: height };
  5003. }
  5004. else if (!isNaN(size)) {
  5005. height = size;
  5006. width = size;
  5007. }
  5008. else {
  5009. Tools.Error("Invalid 'size' parameter !");
  5010. return;
  5011. }
  5012. var scene = camera.getScene();
  5013. var previousCamera = null;
  5014. if (scene.activeCamera !== camera) {
  5015. previousCamera = scene.activeCamera;
  5016. scene.activeCamera = camera;
  5017. }
  5018. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5019. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5020. texture.renderList = scene.meshes;
  5021. texture.onAfterRenderObservable.add(function () {
  5022. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5023. });
  5024. scene.incrementRenderId();
  5025. scene.resetCachedMaterial();
  5026. texture.render(true);
  5027. texture.dispose();
  5028. if (previousCamera) {
  5029. scene.activeCamera = previousCamera;
  5030. }
  5031. camera.getProjectionMatrix(true); // Force cache refresh;
  5032. };
  5033. // XHR response validator for local file scenario
  5034. Tools.ValidateXHRData = function (xhr, dataType) {
  5035. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5036. if (dataType === void 0) { dataType = 7; }
  5037. try {
  5038. if (dataType & 1) {
  5039. if (xhr.responseText && xhr.responseText.length > 0) {
  5040. return true;
  5041. }
  5042. else if (dataType === 1) {
  5043. return false;
  5044. }
  5045. }
  5046. if (dataType & 2) {
  5047. // Check header width and height since there is no "TGA" magic number
  5048. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5049. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5050. return true;
  5051. }
  5052. else if (dataType === 2) {
  5053. return false;
  5054. }
  5055. }
  5056. if (dataType & 4) {
  5057. // Check for the "DDS" magic number
  5058. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5059. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5060. return true;
  5061. }
  5062. else {
  5063. return false;
  5064. }
  5065. }
  5066. }
  5067. catch (e) {
  5068. }
  5069. return false;
  5070. };
  5071. Object.defineProperty(Tools, "NoneLogLevel", {
  5072. get: function () {
  5073. return Tools._NoneLogLevel;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(Tools, "MessageLogLevel", {
  5079. get: function () {
  5080. return Tools._MessageLogLevel;
  5081. },
  5082. enumerable: true,
  5083. configurable: true
  5084. });
  5085. Object.defineProperty(Tools, "WarningLogLevel", {
  5086. get: function () {
  5087. return Tools._WarningLogLevel;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(Tools, "ErrorLogLevel", {
  5093. get: function () {
  5094. return Tools._ErrorLogLevel;
  5095. },
  5096. enumerable: true,
  5097. configurable: true
  5098. });
  5099. Object.defineProperty(Tools, "AllLogLevel", {
  5100. get: function () {
  5101. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Tools._AddLogEntry = function (entry) {
  5107. Tools._LogCache = entry + Tools._LogCache;
  5108. if (Tools.OnNewCacheEntry) {
  5109. Tools.OnNewCacheEntry(entry);
  5110. }
  5111. };
  5112. Tools._FormatMessage = function (message) {
  5113. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5114. var date = new Date();
  5115. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5116. };
  5117. Tools._LogDisabled = function (message) {
  5118. // nothing to do
  5119. };
  5120. Tools._LogEnabled = function (message) {
  5121. var formattedMessage = Tools._FormatMessage(message);
  5122. console.log("BJS - " + formattedMessage);
  5123. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5124. Tools._AddLogEntry(entry);
  5125. };
  5126. Tools._WarnDisabled = function (message) {
  5127. // nothing to do
  5128. };
  5129. Tools._WarnEnabled = function (message) {
  5130. var formattedMessage = Tools._FormatMessage(message);
  5131. console.warn("BJS - " + formattedMessage);
  5132. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5133. Tools._AddLogEntry(entry);
  5134. };
  5135. Tools._ErrorDisabled = function (message) {
  5136. // nothing to do
  5137. };
  5138. Tools._ErrorEnabled = function (message) {
  5139. Tools.errorsCount++;
  5140. var formattedMessage = Tools._FormatMessage(message);
  5141. console.error("BJS - " + formattedMessage);
  5142. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5143. Tools._AddLogEntry(entry);
  5144. };
  5145. Object.defineProperty(Tools, "LogCache", {
  5146. get: function () {
  5147. return Tools._LogCache;
  5148. },
  5149. enumerable: true,
  5150. configurable: true
  5151. });
  5152. Tools.ClearLogCache = function () {
  5153. Tools._LogCache = "";
  5154. Tools.errorsCount = 0;
  5155. };
  5156. Object.defineProperty(Tools, "LogLevels", {
  5157. set: function (level) {
  5158. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5159. Tools.Log = Tools._LogEnabled;
  5160. }
  5161. else {
  5162. Tools.Log = Tools._LogDisabled;
  5163. }
  5164. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5165. Tools.Warn = Tools._WarnEnabled;
  5166. }
  5167. else {
  5168. Tools.Warn = Tools._WarnDisabled;
  5169. }
  5170. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5171. Tools.Error = Tools._ErrorEnabled;
  5172. }
  5173. else {
  5174. Tools.Error = Tools._ErrorDisabled;
  5175. }
  5176. },
  5177. enumerable: true,
  5178. configurable: true
  5179. });
  5180. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5181. get: function () {
  5182. return Tools._PerformanceNoneLogLevel;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5188. get: function () {
  5189. return Tools._PerformanceUserMarkLogLevel;
  5190. },
  5191. enumerable: true,
  5192. configurable: true
  5193. });
  5194. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5195. get: function () {
  5196. return Tools._PerformanceConsoleLogLevel;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5202. set: function (level) {
  5203. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5204. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5205. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5206. return;
  5207. }
  5208. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5209. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5210. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5211. return;
  5212. }
  5213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5215. },
  5216. enumerable: true,
  5217. configurable: true
  5218. });
  5219. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5220. };
  5221. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5222. };
  5223. Tools._StartUserMark = function (counterName, condition) {
  5224. if (condition === void 0) { condition = true; }
  5225. if (!condition || !Tools._performance.mark) {
  5226. return;
  5227. }
  5228. Tools._performance.mark(counterName + "-Begin");
  5229. };
  5230. Tools._EndUserMark = function (counterName, condition) {
  5231. if (condition === void 0) { condition = true; }
  5232. if (!condition || !Tools._performance.mark) {
  5233. return;
  5234. }
  5235. Tools._performance.mark(counterName + "-End");
  5236. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5237. };
  5238. Tools._StartPerformanceConsole = function (counterName, condition) {
  5239. if (condition === void 0) { condition = true; }
  5240. if (!condition) {
  5241. return;
  5242. }
  5243. Tools._StartUserMark(counterName, condition);
  5244. if (console.time) {
  5245. console.time(counterName);
  5246. }
  5247. };
  5248. Tools._EndPerformanceConsole = function (counterName, condition) {
  5249. if (condition === void 0) { condition = true; }
  5250. if (!condition) {
  5251. return;
  5252. }
  5253. Tools._EndUserMark(counterName, condition);
  5254. if (console.time) {
  5255. console.timeEnd(counterName);
  5256. }
  5257. };
  5258. Object.defineProperty(Tools, "Now", {
  5259. get: function () {
  5260. if (window.performance && window.performance.now) {
  5261. return window.performance.now();
  5262. }
  5263. return new Date().getTime();
  5264. },
  5265. enumerable: true,
  5266. configurable: true
  5267. });
  5268. /**
  5269. * This method will return the name of the class used to create the instance of the given object.
  5270. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5271. * @param object the object to get the class name from
  5272. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5273. */
  5274. Tools.getClassName = function (object, isType) {
  5275. if (isType === void 0) { isType = false; }
  5276. var name = null;
  5277. if (!isType && object.getClassName) {
  5278. name = object.getClassName();
  5279. }
  5280. else {
  5281. if (object instanceof Object) {
  5282. var classObj = isType ? object : Object.getPrototypeOf(object);
  5283. name = classObj.constructor["__bjsclassName__"];
  5284. }
  5285. if (!name) {
  5286. name = typeof object;
  5287. }
  5288. }
  5289. return name;
  5290. };
  5291. Tools.first = function (array, predicate) {
  5292. for (var _i = 0; _i < array.length; _i++) {
  5293. var el = array[_i];
  5294. if (predicate(el)) {
  5295. return el;
  5296. }
  5297. }
  5298. };
  5299. /**
  5300. * 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.
  5301. * @param array
  5302. */
  5303. Tools.arrayOrStringFeeder = function (array) {
  5304. return function (index) {
  5305. if (index >= array.length) {
  5306. return null;
  5307. }
  5308. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5309. if (val && val.getHashCode) {
  5310. val = val.getHashCode();
  5311. }
  5312. if (typeof val === "string") {
  5313. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5314. }
  5315. return val;
  5316. };
  5317. };
  5318. /**
  5319. * Compute the hashCode of a stream of number
  5320. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5321. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5322. * @return the hash code computed
  5323. */
  5324. Tools.hashCodeFromStream = function (feeder) {
  5325. // Based from here: http://stackoverflow.com/a/7616484/802124
  5326. var hash = 0;
  5327. var index = 0;
  5328. var chr = feeder(index++);
  5329. while (chr != null) {
  5330. hash = ((hash << 5) - hash) + chr;
  5331. hash |= 0; // Convert to 32bit integer
  5332. chr = feeder(index++);
  5333. }
  5334. return hash;
  5335. };
  5336. Tools.BaseUrl = "";
  5337. Tools.CorsBehavior = "anonymous";
  5338. Tools.UseFallbackTexture = true;
  5339. // Logs
  5340. Tools._NoneLogLevel = 0;
  5341. Tools._MessageLogLevel = 1;
  5342. Tools._WarningLogLevel = 2;
  5343. Tools._ErrorLogLevel = 4;
  5344. Tools._LogCache = "";
  5345. Tools.errorsCount = 0;
  5346. Tools.Log = Tools._LogEnabled;
  5347. Tools.Warn = Tools._WarnEnabled;
  5348. Tools.Error = Tools._ErrorEnabled;
  5349. // Performances
  5350. Tools._PerformanceNoneLogLevel = 0;
  5351. Tools._PerformanceUserMarkLogLevel = 1;
  5352. Tools._PerformanceConsoleLogLevel = 2;
  5353. Tools._performance = window.performance;
  5354. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5355. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5356. return Tools;
  5357. })();
  5358. BABYLON.Tools = Tools;
  5359. /**
  5360. * This class is used to track a performance counter which is number based.
  5361. * The user has access to many properties which give statistics of different nature
  5362. *
  5363. * The implementer can track two kinds of Performance Counter: time and count
  5364. * 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.
  5365. * 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.
  5366. */
  5367. var PerfCounter = (function () {
  5368. function PerfCounter() {
  5369. this._startMonitoringTime = 0;
  5370. this._min = 0;
  5371. this._max = 0;
  5372. this._average = 0;
  5373. this._lastSecAverage = 0;
  5374. this._current = 0;
  5375. this._totalValueCount = 0;
  5376. this._totalAccumulated = 0;
  5377. this._lastSecAccumulated = 0;
  5378. this._lastSecTime = 0;
  5379. this._lastSecValueCount = 0;
  5380. }
  5381. Object.defineProperty(PerfCounter.prototype, "min", {
  5382. /**
  5383. * Returns the smallest value ever
  5384. */
  5385. get: function () {
  5386. return this._min;
  5387. },
  5388. enumerable: true,
  5389. configurable: true
  5390. });
  5391. Object.defineProperty(PerfCounter.prototype, "max", {
  5392. /**
  5393. * Returns the biggest value ever
  5394. */
  5395. get: function () {
  5396. return this._max;
  5397. },
  5398. enumerable: true,
  5399. configurable: true
  5400. });
  5401. Object.defineProperty(PerfCounter.prototype, "average", {
  5402. /**
  5403. * Returns the average value since the performance counter is running
  5404. */
  5405. get: function () {
  5406. return this._average;
  5407. },
  5408. enumerable: true,
  5409. configurable: true
  5410. });
  5411. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5412. /**
  5413. * Returns the average value of the last second the counter was monitored
  5414. */
  5415. get: function () {
  5416. return this._lastSecAverage;
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(PerfCounter.prototype, "current", {
  5422. /**
  5423. * Returns the current value
  5424. */
  5425. get: function () {
  5426. return this._current;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(PerfCounter.prototype, "total", {
  5432. get: function () {
  5433. return this._totalAccumulated;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. /**
  5439. * Call this method to start monitoring a new frame.
  5440. * 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.
  5441. */
  5442. PerfCounter.prototype.fetchNewFrame = function () {
  5443. this._totalValueCount++;
  5444. this._current = 0;
  5445. this._lastSecValueCount++;
  5446. };
  5447. /**
  5448. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5449. * @param newCount the count value to add to the monitored count
  5450. * @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.
  5451. */
  5452. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5453. this._current += newCount;
  5454. if (fetchResult) {
  5455. this._fetchResult();
  5456. }
  5457. };
  5458. /**
  5459. * Start monitoring this performance counter
  5460. */
  5461. PerfCounter.prototype.beginMonitoring = function () {
  5462. this._startMonitoringTime = Tools.Now;
  5463. };
  5464. /**
  5465. * Compute the time lapsed since the previous beginMonitoring() call.
  5466. * @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
  5467. */
  5468. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5469. if (newFrame === void 0) { newFrame = true; }
  5470. if (newFrame) {
  5471. this.fetchNewFrame();
  5472. }
  5473. var currentTime = Tools.Now;
  5474. this._current = currentTime - this._startMonitoringTime;
  5475. if (newFrame) {
  5476. this._fetchResult();
  5477. }
  5478. };
  5479. PerfCounter.prototype._fetchResult = function () {
  5480. this._totalAccumulated += this._current;
  5481. this._lastSecAccumulated += this._current;
  5482. // Min/Max update
  5483. this._min = Math.min(this._min, this._current);
  5484. this._max = Math.max(this._max, this._current);
  5485. this._average = this._totalAccumulated / this._totalValueCount;
  5486. // Reset last sec?
  5487. var now = Tools.Now;
  5488. if ((now - this._lastSecTime) > 1000) {
  5489. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5490. this._lastSecTime = now;
  5491. this._lastSecAccumulated = 0;
  5492. this._lastSecValueCount = 0;
  5493. }
  5494. };
  5495. return PerfCounter;
  5496. })();
  5497. BABYLON.PerfCounter = PerfCounter;
  5498. /**
  5499. * Use this className as a decorator on a given class definition to add it a name.
  5500. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5501. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5502. * @param name
  5503. */
  5504. function className(name) {
  5505. return function (target) {
  5506. target["__bjsclassName__"] = name;
  5507. };
  5508. }
  5509. BABYLON.className = className;
  5510. /**
  5511. * An implementation of a loop for asynchronous functions.
  5512. */
  5513. var AsyncLoop = (function () {
  5514. /**
  5515. * Constroctor.
  5516. * @param iterations the number of iterations.
  5517. * @param _fn the function to run each iteration
  5518. * @param _successCallback the callback that will be called upon succesful execution
  5519. * @param offset starting offset.
  5520. */
  5521. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5522. if (offset === void 0) { offset = 0; }
  5523. this.iterations = iterations;
  5524. this._fn = _fn;
  5525. this._successCallback = _successCallback;
  5526. this.index = offset - 1;
  5527. this._done = false;
  5528. }
  5529. /**
  5530. * Execute the next iteration. Must be called after the last iteration was finished.
  5531. */
  5532. AsyncLoop.prototype.executeNext = function () {
  5533. if (!this._done) {
  5534. if (this.index + 1 < this.iterations) {
  5535. ++this.index;
  5536. this._fn(this);
  5537. }
  5538. else {
  5539. this.breakLoop();
  5540. }
  5541. }
  5542. };
  5543. /**
  5544. * Break the loop and run the success callback.
  5545. */
  5546. AsyncLoop.prototype.breakLoop = function () {
  5547. this._done = true;
  5548. this._successCallback();
  5549. };
  5550. /**
  5551. * Helper function
  5552. */
  5553. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5554. if (offset === void 0) { offset = 0; }
  5555. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5556. loop.executeNext();
  5557. return loop;
  5558. };
  5559. /**
  5560. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5561. * @param iterations total number of iterations
  5562. * @param syncedIterations number of synchronous iterations in each async iteration.
  5563. * @param fn the function to call each iteration.
  5564. * @param callback a success call back that will be called when iterating stops.
  5565. * @param breakFunction a break condition (optional)
  5566. * @param timeout timeout settings for the setTimeout function. default - 0.
  5567. * @constructor
  5568. */
  5569. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5570. if (timeout === void 0) { timeout = 0; }
  5571. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5572. if (breakFunction && breakFunction())
  5573. loop.breakLoop();
  5574. else {
  5575. setTimeout(function () {
  5576. for (var i = 0; i < syncedIterations; ++i) {
  5577. var iteration = (loop.index * syncedIterations) + i;
  5578. if (iteration >= iterations)
  5579. break;
  5580. fn(iteration);
  5581. if (breakFunction && breakFunction()) {
  5582. loop.breakLoop();
  5583. break;
  5584. }
  5585. }
  5586. loop.executeNext();
  5587. }, timeout);
  5588. }
  5589. }, callback);
  5590. };
  5591. return AsyncLoop;
  5592. })();
  5593. BABYLON.AsyncLoop = AsyncLoop;
  5594. })(BABYLON || (BABYLON = {}));
  5595. var BABYLON;
  5596. (function (BABYLON) {
  5597. var Internals;
  5598. (function (Internals) {
  5599. var _AlphaState = (function () {
  5600. function _AlphaState() {
  5601. this._isAlphaBlendDirty = false;
  5602. this._isBlendFunctionParametersDirty = false;
  5603. this._alphaBlend = false;
  5604. this._blendFunctionParameters = new Array(4);
  5605. }
  5606. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5607. get: function () {
  5608. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5609. },
  5610. enumerable: true,
  5611. configurable: true
  5612. });
  5613. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5614. get: function () {
  5615. return this._alphaBlend;
  5616. },
  5617. set: function (value) {
  5618. if (this._alphaBlend === value) {
  5619. return;
  5620. }
  5621. this._alphaBlend = value;
  5622. this._isAlphaBlendDirty = true;
  5623. },
  5624. enumerable: true,
  5625. configurable: true
  5626. });
  5627. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5628. if (this._blendFunctionParameters[0] === value0 &&
  5629. this._blendFunctionParameters[1] === value1 &&
  5630. this._blendFunctionParameters[2] === value2 &&
  5631. this._blendFunctionParameters[3] === value3) {
  5632. return;
  5633. }
  5634. this._blendFunctionParameters[0] = value0;
  5635. this._blendFunctionParameters[1] = value1;
  5636. this._blendFunctionParameters[2] = value2;
  5637. this._blendFunctionParameters[3] = value3;
  5638. this._isBlendFunctionParametersDirty = true;
  5639. };
  5640. _AlphaState.prototype.reset = function () {
  5641. this._alphaBlend = false;
  5642. this._blendFunctionParameters[0] = null;
  5643. this._blendFunctionParameters[1] = null;
  5644. this._blendFunctionParameters[2] = null;
  5645. this._blendFunctionParameters[3] = null;
  5646. this._isAlphaBlendDirty = true;
  5647. this._isBlendFunctionParametersDirty = false;
  5648. };
  5649. _AlphaState.prototype.apply = function (gl) {
  5650. if (!this.isDirty) {
  5651. return;
  5652. }
  5653. // Alpha blend
  5654. if (this._isAlphaBlendDirty) {
  5655. if (this._alphaBlend) {
  5656. gl.enable(gl.BLEND);
  5657. }
  5658. else {
  5659. gl.disable(gl.BLEND);
  5660. }
  5661. this._isAlphaBlendDirty = false;
  5662. }
  5663. // Alpha function
  5664. if (this._isBlendFunctionParametersDirty) {
  5665. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5666. this._isBlendFunctionParametersDirty = false;
  5667. }
  5668. };
  5669. return _AlphaState;
  5670. })();
  5671. Internals._AlphaState = _AlphaState;
  5672. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5673. })(BABYLON || (BABYLON = {}));
  5674. var BABYLON;
  5675. (function (BABYLON) {
  5676. var Internals;
  5677. (function (Internals) {
  5678. var _DepthCullingState = (function () {
  5679. function _DepthCullingState() {
  5680. this._isDepthTestDirty = false;
  5681. this._isDepthMaskDirty = false;
  5682. this._isDepthFuncDirty = false;
  5683. this._isCullFaceDirty = false;
  5684. this._isCullDirty = false;
  5685. this._isZOffsetDirty = false;
  5686. }
  5687. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5688. get: function () {
  5689. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5695. get: function () {
  5696. return this._zOffset;
  5697. },
  5698. set: function (value) {
  5699. if (this._zOffset === value) {
  5700. return;
  5701. }
  5702. this._zOffset = value;
  5703. this._isZOffsetDirty = true;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5709. get: function () {
  5710. return this._cullFace;
  5711. },
  5712. set: function (value) {
  5713. if (this._cullFace === value) {
  5714. return;
  5715. }
  5716. this._cullFace = value;
  5717. this._isCullFaceDirty = true;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5723. get: function () {
  5724. return this._cull;
  5725. },
  5726. set: function (value) {
  5727. if (this._cull === value) {
  5728. return;
  5729. }
  5730. this._cull = value;
  5731. this._isCullDirty = true;
  5732. },
  5733. enumerable: true,
  5734. configurable: true
  5735. });
  5736. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5737. get: function () {
  5738. return this._depthFunc;
  5739. },
  5740. set: function (value) {
  5741. if (this._depthFunc === value) {
  5742. return;
  5743. }
  5744. this._depthFunc = value;
  5745. this._isDepthFuncDirty = true;
  5746. },
  5747. enumerable: true,
  5748. configurable: true
  5749. });
  5750. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5751. get: function () {
  5752. return this._depthMask;
  5753. },
  5754. set: function (value) {
  5755. if (this._depthMask === value) {
  5756. return;
  5757. }
  5758. this._depthMask = value;
  5759. this._isDepthMaskDirty = true;
  5760. },
  5761. enumerable: true,
  5762. configurable: true
  5763. });
  5764. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5765. get: function () {
  5766. return this._depthTest;
  5767. },
  5768. set: function (value) {
  5769. if (this._depthTest === value) {
  5770. return;
  5771. }
  5772. this._depthTest = value;
  5773. this._isDepthTestDirty = true;
  5774. },
  5775. enumerable: true,
  5776. configurable: true
  5777. });
  5778. _DepthCullingState.prototype.reset = function () {
  5779. this._depthMask = true;
  5780. this._depthTest = true;
  5781. this._depthFunc = null;
  5782. this._cullFace = null;
  5783. this._cull = null;
  5784. this._zOffset = 0;
  5785. this._isDepthTestDirty = true;
  5786. this._isDepthMaskDirty = true;
  5787. this._isDepthFuncDirty = false;
  5788. this._isCullFaceDirty = false;
  5789. this._isCullDirty = false;
  5790. this._isZOffsetDirty = false;
  5791. };
  5792. _DepthCullingState.prototype.apply = function (gl) {
  5793. if (!this.isDirty) {
  5794. return;
  5795. }
  5796. // Cull
  5797. if (this._isCullDirty) {
  5798. if (this.cull) {
  5799. gl.enable(gl.CULL_FACE);
  5800. }
  5801. else {
  5802. gl.disable(gl.CULL_FACE);
  5803. }
  5804. this._isCullDirty = false;
  5805. }
  5806. // Cull face
  5807. if (this._isCullFaceDirty) {
  5808. gl.cullFace(this.cullFace);
  5809. this._isCullFaceDirty = false;
  5810. }
  5811. // Depth mask
  5812. if (this._isDepthMaskDirty) {
  5813. gl.depthMask(this.depthMask);
  5814. this._isDepthMaskDirty = false;
  5815. }
  5816. // Depth test
  5817. if (this._isDepthTestDirty) {
  5818. if (this.depthTest) {
  5819. gl.enable(gl.DEPTH_TEST);
  5820. }
  5821. else {
  5822. gl.disable(gl.DEPTH_TEST);
  5823. }
  5824. this._isDepthTestDirty = false;
  5825. }
  5826. // Depth func
  5827. if (this._isDepthFuncDirty) {
  5828. gl.depthFunc(this.depthFunc);
  5829. this._isDepthFuncDirty = false;
  5830. }
  5831. // zOffset
  5832. if (this._isZOffsetDirty) {
  5833. if (this.zOffset) {
  5834. gl.enable(gl.POLYGON_OFFSET_FILL);
  5835. gl.polygonOffset(this.zOffset, 0);
  5836. }
  5837. else {
  5838. gl.disable(gl.POLYGON_OFFSET_FILL);
  5839. }
  5840. this._isZOffsetDirty = false;
  5841. }
  5842. };
  5843. return _DepthCullingState;
  5844. })();
  5845. Internals._DepthCullingState = _DepthCullingState;
  5846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5847. })(BABYLON || (BABYLON = {}));
  5848. var BABYLON;
  5849. (function (BABYLON) {
  5850. var compileShader = function (gl, source, type, defines) {
  5851. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5852. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5853. gl.compileShader(shader);
  5854. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5855. throw new Error(gl.getShaderInfoLog(shader));
  5856. }
  5857. return shader;
  5858. };
  5859. var HALF_FLOAT_OES = 0x8D61;
  5860. var getWebGLTextureType = function (gl, type) {
  5861. if (type === Engine.TEXTURETYPE_FLOAT) {
  5862. return gl.FLOAT;
  5863. }
  5864. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5865. // Add Half Float Constant.
  5866. return HALF_FLOAT_OES;
  5867. }
  5868. return gl.UNSIGNED_BYTE;
  5869. };
  5870. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5871. var magFilter = gl.NEAREST;
  5872. var minFilter = gl.NEAREST;
  5873. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5874. magFilter = gl.LINEAR;
  5875. if (generateMipMaps) {
  5876. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5877. }
  5878. else {
  5879. minFilter = gl.LINEAR;
  5880. }
  5881. }
  5882. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5883. magFilter = gl.LINEAR;
  5884. if (generateMipMaps) {
  5885. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5886. }
  5887. else {
  5888. minFilter = gl.LINEAR;
  5889. }
  5890. }
  5891. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5892. magFilter = gl.NEAREST;
  5893. if (generateMipMaps) {
  5894. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5895. }
  5896. else {
  5897. minFilter = gl.NEAREST;
  5898. }
  5899. }
  5900. return {
  5901. min: minFilter,
  5902. mag: magFilter
  5903. };
  5904. };
  5905. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5907. var engine = scene.getEngine();
  5908. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5909. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5910. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  5911. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5912. texture._baseWidth = width;
  5913. texture._baseHeight = height;
  5914. texture._width = potWidth;
  5915. texture._height = potHeight;
  5916. texture.isReady = true;
  5917. processFunction(potWidth, potHeight);
  5918. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5920. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5921. if (!noMipmap && !isCompressed) {
  5922. gl.generateMipmap(gl.TEXTURE_2D);
  5923. }
  5924. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  5925. engine.resetTextureCache();
  5926. scene._removePendingData(texture);
  5927. if (onLoad) {
  5928. onLoad();
  5929. }
  5930. };
  5931. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5932. var img;
  5933. var onload = function () {
  5934. loadedImages[index] = img;
  5935. loadedImages._internalCount++;
  5936. scene._removePendingData(img);
  5937. if (loadedImages._internalCount === 6) {
  5938. onfinish(loadedImages);
  5939. }
  5940. };
  5941. var onerror = function () {
  5942. scene._removePendingData(img);
  5943. };
  5944. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5945. scene._addPendingData(img);
  5946. };
  5947. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5948. var loadedImages = [];
  5949. loadedImages._internalCount = 0;
  5950. for (var index = 0; index < 6; index++) {
  5951. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5952. }
  5953. };
  5954. var InstancingAttributeInfo = (function () {
  5955. function InstancingAttributeInfo() {
  5956. }
  5957. return InstancingAttributeInfo;
  5958. })();
  5959. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  5960. var EngineCapabilities = (function () {
  5961. function EngineCapabilities() {
  5962. }
  5963. return EngineCapabilities;
  5964. })();
  5965. BABYLON.EngineCapabilities = EngineCapabilities;
  5966. /**
  5967. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5968. */
  5969. var Engine = (function () {
  5970. /**
  5971. * @constructor
  5972. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5973. * @param {boolean} [antialias] - enable antialias
  5974. * @param options - further options to be sent to the getContext function
  5975. */
  5976. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5977. var _this = this;
  5978. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5979. // Public members
  5980. this.isFullscreen = false;
  5981. this.isPointerLock = false;
  5982. this.cullBackFaces = true;
  5983. this.renderEvenInBackground = true;
  5984. // To enable/disable IDB support and avoid XHR on .manifest
  5985. this.enableOfflineSupport = true;
  5986. this.scenes = new Array();
  5987. this._windowIsBackground = false;
  5988. this._webGLVersion = "1.0";
  5989. this._drawCalls = new BABYLON.PerfCounter();
  5990. this._renderingQueueLaunched = false;
  5991. this._activeRenderLoops = [];
  5992. // FPS
  5993. this.fpsRange = 60;
  5994. this.previousFramesDuration = [];
  5995. this.fps = 60;
  5996. this.deltaTime = 0;
  5997. // States
  5998. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5999. this._alphaState = new BABYLON.Internals._AlphaState();
  6000. this._alphaMode = Engine.ALPHA_DISABLE;
  6001. // Cache
  6002. this._loadedTexturesCache = new Array();
  6003. this._maxTextureChannels = 16;
  6004. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6005. this._compiledEffects = {};
  6006. this._uintIndicesCurrentlySet = false;
  6007. this._currentBoundBuffer = new Array();
  6008. this._currentBufferPointers = [];
  6009. this._currentInstanceLocations = new Array();
  6010. this._currentInstanceBuffers = new Array();
  6011. this._renderingCanvas = canvas;
  6012. this._externalData = new BABYLON.StringDictionary();
  6013. options = options || {};
  6014. options.antialias = antialias;
  6015. if (options.preserveDrawingBuffer === undefined) {
  6016. options.preserveDrawingBuffer = false;
  6017. }
  6018. // Checks if some of the format renders first to allow the use of webgl inspector.
  6019. var renderToFullFloat = this._canRenderToFloatTexture();
  6020. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6021. // GL
  6022. //try {
  6023. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6024. // if (this._gl) {
  6025. // this._webGLVersion = "2.0";
  6026. // }
  6027. //} catch (e) {
  6028. // // Do nothing
  6029. //}
  6030. if (!this._gl) {
  6031. try {
  6032. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6033. }
  6034. catch (e) {
  6035. throw new Error("WebGL not supported");
  6036. }
  6037. }
  6038. if (!this._gl) {
  6039. throw new Error("WebGL not supported");
  6040. }
  6041. this._onBlur = function () {
  6042. _this._windowIsBackground = true;
  6043. };
  6044. this._onFocus = function () {
  6045. _this._windowIsBackground = false;
  6046. };
  6047. window.addEventListener("blur", this._onBlur);
  6048. window.addEventListener("focus", this._onFocus);
  6049. // Viewport
  6050. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6051. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6052. this.resize();
  6053. // Caps
  6054. this._caps = new EngineCapabilities();
  6055. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6056. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6057. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6058. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6059. // Infos
  6060. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6061. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6062. if (rendererInfo != null) {
  6063. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6064. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6065. }
  6066. if (!this._glVendor) {
  6067. this._glVendor = "Unknown vendor";
  6068. }
  6069. if (!this._glRenderer) {
  6070. this._glRenderer = "Unknown renderer";
  6071. }
  6072. // Extensions
  6073. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6074. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6075. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6076. 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');
  6077. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6078. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6079. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6080. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6081. this._caps.highPrecisionShaderSupported = true;
  6082. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6083. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6084. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6085. this._caps.textureFloatRender = renderToFullFloat;
  6086. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6087. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6088. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6089. if (this._gl.getShaderPrecisionFormat) {
  6090. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6091. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6092. }
  6093. // Depth buffer
  6094. this.setDepthBuffer(true);
  6095. this.setDepthFunctionToLessOrEqual();
  6096. this.setDepthWrite(true);
  6097. // Fullscreen
  6098. this._onFullscreenChange = function () {
  6099. if (document.fullscreen !== undefined) {
  6100. _this.isFullscreen = document.fullscreen;
  6101. }
  6102. else if (document.mozFullScreen !== undefined) {
  6103. _this.isFullscreen = document.mozFullScreen;
  6104. }
  6105. else if (document.webkitIsFullScreen !== undefined) {
  6106. _this.isFullscreen = document.webkitIsFullScreen;
  6107. }
  6108. else if (document.msIsFullScreen !== undefined) {
  6109. _this.isFullscreen = document.msIsFullScreen;
  6110. }
  6111. // Pointer lock
  6112. if (_this.isFullscreen && _this._pointerLockRequested) {
  6113. canvas.requestPointerLock = canvas.requestPointerLock ||
  6114. canvas.msRequestPointerLock ||
  6115. canvas.mozRequestPointerLock ||
  6116. canvas.webkitRequestPointerLock;
  6117. if (canvas.requestPointerLock) {
  6118. canvas.requestPointerLock();
  6119. }
  6120. }
  6121. };
  6122. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6123. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6124. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6125. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6126. // Pointer lock
  6127. this._onPointerLockChange = function () {
  6128. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6129. document.webkitPointerLockElement === canvas ||
  6130. document.msPointerLockElement === canvas ||
  6131. document.pointerLockElement === canvas);
  6132. };
  6133. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6134. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6135. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6136. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6137. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6138. Engine.audioEngine = new BABYLON.AudioEngine();
  6139. }
  6140. //default loading screen
  6141. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6142. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6143. }
  6144. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6145. get: function () {
  6146. return Engine._ALPHA_DISABLE;
  6147. },
  6148. enumerable: true,
  6149. configurable: true
  6150. });
  6151. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6152. get: function () {
  6153. return Engine._ALPHA_ONEONE;
  6154. },
  6155. enumerable: true,
  6156. configurable: true
  6157. });
  6158. Object.defineProperty(Engine, "ALPHA_ADD", {
  6159. get: function () {
  6160. return Engine._ALPHA_ADD;
  6161. },
  6162. enumerable: true,
  6163. configurable: true
  6164. });
  6165. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6166. get: function () {
  6167. return Engine._ALPHA_COMBINE;
  6168. },
  6169. enumerable: true,
  6170. configurable: true
  6171. });
  6172. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6173. get: function () {
  6174. return Engine._ALPHA_SUBTRACT;
  6175. },
  6176. enumerable: true,
  6177. configurable: true
  6178. });
  6179. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6180. get: function () {
  6181. return Engine._ALPHA_MULTIPLY;
  6182. },
  6183. enumerable: true,
  6184. configurable: true
  6185. });
  6186. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6187. get: function () {
  6188. return Engine._ALPHA_MAXIMIZED;
  6189. },
  6190. enumerable: true,
  6191. configurable: true
  6192. });
  6193. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6194. get: function () {
  6195. return Engine._DELAYLOADSTATE_NONE;
  6196. },
  6197. enumerable: true,
  6198. configurable: true
  6199. });
  6200. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6201. get: function () {
  6202. return Engine._DELAYLOADSTATE_LOADED;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6208. get: function () {
  6209. return Engine._DELAYLOADSTATE_LOADING;
  6210. },
  6211. enumerable: true,
  6212. configurable: true
  6213. });
  6214. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6215. get: function () {
  6216. return Engine._DELAYLOADSTATE_NOTLOADED;
  6217. },
  6218. enumerable: true,
  6219. configurable: true
  6220. });
  6221. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6222. get: function () {
  6223. return Engine._TEXTUREFORMAT_ALPHA;
  6224. },
  6225. enumerable: true,
  6226. configurable: true
  6227. });
  6228. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6229. get: function () {
  6230. return Engine._TEXTUREFORMAT_LUMINANCE;
  6231. },
  6232. enumerable: true,
  6233. configurable: true
  6234. });
  6235. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6236. get: function () {
  6237. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6238. },
  6239. enumerable: true,
  6240. configurable: true
  6241. });
  6242. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6243. get: function () {
  6244. return Engine._TEXTUREFORMAT_RGB;
  6245. },
  6246. enumerable: true,
  6247. configurable: true
  6248. });
  6249. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6250. get: function () {
  6251. return Engine._TEXTUREFORMAT_RGBA;
  6252. },
  6253. enumerable: true,
  6254. configurable: true
  6255. });
  6256. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6257. get: function () {
  6258. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6259. },
  6260. enumerable: true,
  6261. configurable: true
  6262. });
  6263. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6264. get: function () {
  6265. return Engine._TEXTURETYPE_FLOAT;
  6266. },
  6267. enumerable: true,
  6268. configurable: true
  6269. });
  6270. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6271. get: function () {
  6272. return Engine._TEXTURETYPE_HALF_FLOAT;
  6273. },
  6274. enumerable: true,
  6275. configurable: true
  6276. });
  6277. Object.defineProperty(Engine, "Version", {
  6278. get: function () {
  6279. return "2.5-alpha";
  6280. },
  6281. enumerable: true,
  6282. configurable: true
  6283. });
  6284. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6285. get: function () {
  6286. return this._webGLVersion;
  6287. },
  6288. enumerable: true,
  6289. configurable: true
  6290. });
  6291. Engine.prototype._prepareWorkingCanvas = function () {
  6292. if (this._workingCanvas) {
  6293. return;
  6294. }
  6295. this._workingCanvas = document.createElement("canvas");
  6296. this._workingContext = this._workingCanvas.getContext("2d");
  6297. };
  6298. Engine.prototype.resetTextureCache = function () {
  6299. for (var index = 0; index < this._maxTextureChannels; index++) {
  6300. this._activeTexturesCache[index] = null;
  6301. }
  6302. };
  6303. Engine.prototype.getGlInfo = function () {
  6304. return {
  6305. vendor: this._glVendor,
  6306. renderer: this._glRenderer,
  6307. version: this._glVersion
  6308. };
  6309. };
  6310. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6311. if (useScreen === void 0) { useScreen = false; }
  6312. var viewport = camera.viewport;
  6313. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6314. };
  6315. Engine.prototype.getRenderWidth = function (useScreen) {
  6316. if (useScreen === void 0) { useScreen = false; }
  6317. if (!useScreen && this._currentRenderTarget) {
  6318. return this._currentRenderTarget._width;
  6319. }
  6320. return this._renderingCanvas.width;
  6321. };
  6322. Engine.prototype.getRenderHeight = function (useScreen) {
  6323. if (useScreen === void 0) { useScreen = false; }
  6324. if (!useScreen && this._currentRenderTarget) {
  6325. return this._currentRenderTarget._height;
  6326. }
  6327. return this._renderingCanvas.height;
  6328. };
  6329. Engine.prototype.getRenderingCanvas = function () {
  6330. return this._renderingCanvas;
  6331. };
  6332. Engine.prototype.getRenderingCanvasClientRect = function () {
  6333. return this._renderingCanvas.getBoundingClientRect();
  6334. };
  6335. Engine.prototype.setHardwareScalingLevel = function (level) {
  6336. this._hardwareScalingLevel = level;
  6337. this.resize();
  6338. };
  6339. Engine.prototype.getHardwareScalingLevel = function () {
  6340. return this._hardwareScalingLevel;
  6341. };
  6342. Engine.prototype.getLoadedTexturesCache = function () {
  6343. return this._loadedTexturesCache;
  6344. };
  6345. Engine.prototype.getCaps = function () {
  6346. return this._caps;
  6347. };
  6348. Object.defineProperty(Engine.prototype, "drawCalls", {
  6349. get: function () {
  6350. return this._drawCalls.current;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6356. get: function () {
  6357. return this._drawCalls;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Engine.prototype.getDepthFunction = function () {
  6363. return this._depthCullingState.depthFunc;
  6364. };
  6365. Engine.prototype.setDepthFunction = function (depthFunc) {
  6366. this._depthCullingState.depthFunc = depthFunc;
  6367. };
  6368. Engine.prototype.setDepthFunctionToGreater = function () {
  6369. this._depthCullingState.depthFunc = this._gl.GREATER;
  6370. };
  6371. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6372. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6373. };
  6374. Engine.prototype.setDepthFunctionToLess = function () {
  6375. this._depthCullingState.depthFunc = this._gl.LESS;
  6376. };
  6377. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6378. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6379. };
  6380. /**
  6381. * stop executing a render loop function and remove it from the execution array
  6382. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6383. */
  6384. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6385. if (!renderFunction) {
  6386. this._activeRenderLoops = [];
  6387. return;
  6388. }
  6389. var index = this._activeRenderLoops.indexOf(renderFunction);
  6390. if (index >= 0) {
  6391. this._activeRenderLoops.splice(index, 1);
  6392. }
  6393. };
  6394. Engine.prototype._renderLoop = function () {
  6395. var shouldRender = true;
  6396. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6397. shouldRender = false;
  6398. }
  6399. if (shouldRender) {
  6400. // Start new frame
  6401. this.beginFrame();
  6402. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6403. var renderFunction = this._activeRenderLoops[index];
  6404. renderFunction();
  6405. }
  6406. // Present
  6407. this.endFrame();
  6408. }
  6409. if (this._activeRenderLoops.length > 0) {
  6410. // Register new frame
  6411. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6412. }
  6413. else {
  6414. this._renderingQueueLaunched = false;
  6415. }
  6416. };
  6417. /**
  6418. * Register and execute a render loop. The engine can have more than one render function.
  6419. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6420. * @example
  6421. * engine.runRenderLoop(function () {
  6422. * scene.render()
  6423. * })
  6424. */
  6425. Engine.prototype.runRenderLoop = function (renderFunction) {
  6426. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6427. return;
  6428. }
  6429. this._activeRenderLoops.push(renderFunction);
  6430. if (!this._renderingQueueLaunched) {
  6431. this._renderingQueueLaunched = true;
  6432. this._bindedRenderFunction = this._renderLoop.bind(this);
  6433. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6434. }
  6435. };
  6436. /**
  6437. * Toggle full screen mode.
  6438. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6439. * @param {any} options - an options object to be sent to the requestFullscreen function
  6440. */
  6441. Engine.prototype.switchFullscreen = function (requestPointerLock, options) {
  6442. if (this.isFullscreen) {
  6443. BABYLON.Tools.ExitFullscreen();
  6444. }
  6445. else {
  6446. this._pointerLockRequested = requestPointerLock;
  6447. BABYLON.Tools.RequestFullscreen(this._renderingCanvas, options);
  6448. }
  6449. };
  6450. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  6451. this.applyStates();
  6452. if (backBuffer) {
  6453. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6454. }
  6455. if (depthStencil && this._depthCullingState.depthMask) {
  6456. this._gl.clearDepth(1.0);
  6457. }
  6458. var mode = 0;
  6459. if (backBuffer) {
  6460. mode |= this._gl.COLOR_BUFFER_BIT;
  6461. }
  6462. if (depthStencil && this._depthCullingState.depthMask) {
  6463. mode |= this._gl.DEPTH_BUFFER_BIT;
  6464. }
  6465. this._gl.clear(mode);
  6466. };
  6467. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6468. var gl = this._gl;
  6469. // Save state
  6470. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6471. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6472. // Change state
  6473. gl.enable(gl.SCISSOR_TEST);
  6474. gl.scissor(x, y, width, height);
  6475. // Clear
  6476. this.clear(clearColor, true, true);
  6477. // Restore state
  6478. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6479. if (curScissor === true) {
  6480. gl.enable(gl.SCISSOR_TEST);
  6481. }
  6482. else {
  6483. gl.disable(gl.SCISSOR_TEST);
  6484. }
  6485. };
  6486. /**
  6487. * Set the WebGL's viewport
  6488. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6489. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6490. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6491. */
  6492. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6493. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6494. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6495. var x = viewport.x || 0;
  6496. var y = viewport.y || 0;
  6497. this._cachedViewport = viewport;
  6498. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6499. };
  6500. /**
  6501. * Directly set the WebGL Viewport
  6502. * The x, y, width & height are directly passed to the WebGL call
  6503. * @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.
  6504. */
  6505. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6506. var currentViewport = this._cachedViewport;
  6507. this._cachedViewport = null;
  6508. this._gl.viewport(x, y, width, height);
  6509. return currentViewport;
  6510. };
  6511. Engine.prototype.beginFrame = function () {
  6512. this._measureFps();
  6513. };
  6514. Engine.prototype.endFrame = function () {
  6515. //this.flushFramebuffer();
  6516. };
  6517. /**
  6518. * resize the view according to the canvas' size.
  6519. * @example
  6520. * window.addEventListener("resize", function () {
  6521. * engine.resize();
  6522. * });
  6523. */
  6524. Engine.prototype.resize = function () {
  6525. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6526. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6527. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6528. for (var index = 0; index < this.scenes.length; index++) {
  6529. var scene = this.scenes[index];
  6530. if (scene.debugLayer.isVisible()) {
  6531. scene.debugLayer._syncPositions();
  6532. }
  6533. }
  6534. };
  6535. /**
  6536. * force a specific size of the canvas
  6537. * @param {number} width - the new canvas' width
  6538. * @param {number} height - the new canvas' height
  6539. */
  6540. Engine.prototype.setSize = function (width, height) {
  6541. this._renderingCanvas.width = width;
  6542. this._renderingCanvas.height = height;
  6543. for (var index = 0; index < this.scenes.length; index++) {
  6544. var scene = this.scenes[index];
  6545. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6546. var cam = scene.cameras[camIndex];
  6547. cam._currentRenderId = 0;
  6548. }
  6549. }
  6550. };
  6551. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6552. this._currentRenderTarget = texture;
  6553. var gl = this._gl;
  6554. this.bindUnboundFramebuffer(texture._framebuffer);
  6555. if (texture.isCube) {
  6556. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6557. }
  6558. else {
  6559. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6560. }
  6561. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6562. this.wipeCaches();
  6563. };
  6564. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6565. if (this._currentFramebuffer !== framebuffer) {
  6566. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6567. this._currentFramebuffer = framebuffer;
  6568. }
  6569. };
  6570. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6571. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6572. this._currentRenderTarget = null;
  6573. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6574. var gl = this._gl;
  6575. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6576. gl.generateMipmap(gl.TEXTURE_2D);
  6577. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6578. }
  6579. this.bindUnboundFramebuffer(null);
  6580. };
  6581. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6582. if (texture.generateMipMaps) {
  6583. var gl = this._gl;
  6584. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6585. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6586. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6587. }
  6588. };
  6589. Engine.prototype.flushFramebuffer = function () {
  6590. this._gl.flush();
  6591. };
  6592. Engine.prototype.restoreDefaultFramebuffer = function () {
  6593. this._currentRenderTarget = null;
  6594. this.bindUnboundFramebuffer(null);
  6595. this.setViewport(this._cachedViewport);
  6596. this.wipeCaches();
  6597. };
  6598. // VBOs
  6599. Engine.prototype._resetVertexBufferBinding = function () {
  6600. this.bindArrayBuffer(null);
  6601. this._cachedVertexBuffers = null;
  6602. };
  6603. Engine.prototype.createVertexBuffer = function (vertices) {
  6604. var vbo = this._gl.createBuffer();
  6605. this.bindArrayBuffer(vbo);
  6606. if (vertices instanceof Float32Array) {
  6607. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6608. }
  6609. else {
  6610. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6611. }
  6612. this._resetVertexBufferBinding();
  6613. vbo.references = 1;
  6614. return vbo;
  6615. };
  6616. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6617. var vbo = this._gl.createBuffer();
  6618. this.bindArrayBuffer(vbo);
  6619. if (vertices instanceof Float32Array) {
  6620. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6621. }
  6622. else {
  6623. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6624. }
  6625. this._resetVertexBufferBinding();
  6626. vbo.references = 1;
  6627. return vbo;
  6628. };
  6629. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6630. this.bindArrayBuffer(vertexBuffer);
  6631. if (offset === undefined) {
  6632. offset = 0;
  6633. }
  6634. if (count === undefined) {
  6635. if (vertices instanceof Float32Array) {
  6636. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6637. }
  6638. else {
  6639. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6640. }
  6641. }
  6642. else {
  6643. if (vertices instanceof Float32Array) {
  6644. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6645. }
  6646. else {
  6647. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6648. }
  6649. }
  6650. this._resetVertexBufferBinding();
  6651. };
  6652. Engine.prototype._resetIndexBufferBinding = function () {
  6653. this.bindIndexBuffer(null);
  6654. this._cachedIndexBuffer = null;
  6655. };
  6656. Engine.prototype.createIndexBuffer = function (indices) {
  6657. var vbo = this._gl.createBuffer();
  6658. this.bindIndexBuffer(vbo);
  6659. // Check for 32 bits indices
  6660. var arrayBuffer;
  6661. var need32Bits = false;
  6662. if (this._caps.uintIndices) {
  6663. for (var index = 0; index < indices.length; index++) {
  6664. if (indices[index] > 65535) {
  6665. need32Bits = true;
  6666. break;
  6667. }
  6668. }
  6669. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6670. }
  6671. else {
  6672. arrayBuffer = new Uint16Array(indices);
  6673. }
  6674. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6675. this._resetIndexBufferBinding();
  6676. vbo.references = 1;
  6677. vbo.is32Bits = need32Bits;
  6678. return vbo;
  6679. };
  6680. Engine.prototype.bindArrayBuffer = function (buffer) {
  6681. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  6682. };
  6683. Engine.prototype.bindIndexBuffer = function (buffer) {
  6684. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  6685. };
  6686. Engine.prototype.bindBuffer = function (buffer, target) {
  6687. if (this._currentBoundBuffer[target] !== buffer) {
  6688. this._gl.bindBuffer(target, buffer);
  6689. this._currentBoundBuffer[target] = buffer;
  6690. }
  6691. };
  6692. Engine.prototype.updateArrayBuffer = function (data) {
  6693. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6694. };
  6695. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  6696. var pointer = this._currentBufferPointers[indx];
  6697. var changed = false;
  6698. if (!pointer) {
  6699. changed = true;
  6700. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  6701. }
  6702. else {
  6703. if (pointer.buffer !== buffer) {
  6704. pointer.buffer = buffer;
  6705. changed = true;
  6706. }
  6707. if (pointer.size !== size) {
  6708. pointer.size = size;
  6709. changed = true;
  6710. }
  6711. if (pointer.type !== type) {
  6712. pointer.type = type;
  6713. changed = true;
  6714. }
  6715. if (pointer.normalized !== normalized) {
  6716. pointer.normalized = normalized;
  6717. changed = true;
  6718. }
  6719. if (pointer.stride !== stride) {
  6720. pointer.stride = stride;
  6721. changed = true;
  6722. }
  6723. if (pointer.offset !== offset) {
  6724. pointer.offset = offset;
  6725. changed = true;
  6726. }
  6727. }
  6728. if (changed) {
  6729. this.bindArrayBuffer(buffer);
  6730. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  6731. }
  6732. };
  6733. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6734. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6735. this._cachedVertexBuffers = vertexBuffer;
  6736. this._cachedEffectForVertexBuffers = effect;
  6737. var offset = 0;
  6738. for (var index = 0; index < vertexDeclaration.length; index++) {
  6739. var order = effect.getAttributeLocation(index);
  6740. if (order >= 0) {
  6741. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6742. }
  6743. offset += vertexDeclaration[index] * 4;
  6744. }
  6745. }
  6746. if (this._cachedIndexBuffer !== indexBuffer) {
  6747. this._cachedIndexBuffer = indexBuffer;
  6748. this.bindIndexBuffer(indexBuffer);
  6749. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6750. }
  6751. };
  6752. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  6753. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6754. this._cachedVertexBuffers = vertexBuffers;
  6755. this._cachedEffectForVertexBuffers = effect;
  6756. var attributes = effect.getAttributesNames();
  6757. for (var index = 0; index < attributes.length; index++) {
  6758. var order = effect.getAttributeLocation(index);
  6759. if (order >= 0) {
  6760. var vertexBuffer = vertexBuffers[attributes[index]];
  6761. if (!vertexBuffer) {
  6762. continue;
  6763. }
  6764. var buffer = vertexBuffer.getBuffer();
  6765. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  6766. if (vertexBuffer.getIsInstanced()) {
  6767. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  6768. this._currentInstanceLocations.push(order);
  6769. this._currentInstanceBuffers.push(buffer);
  6770. }
  6771. }
  6772. }
  6773. }
  6774. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6775. this._cachedIndexBuffer = indexBuffer;
  6776. this.bindIndexBuffer(indexBuffer);
  6777. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6778. }
  6779. };
  6780. Engine.prototype.unbindInstanceAttributes = function () {
  6781. var boundBuffer;
  6782. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  6783. var instancesBuffer = this._currentInstanceBuffers[i];
  6784. if (boundBuffer != instancesBuffer) {
  6785. boundBuffer = instancesBuffer;
  6786. this.bindArrayBuffer(instancesBuffer);
  6787. }
  6788. var offsetLocation = this._currentInstanceLocations[i];
  6789. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6790. }
  6791. this._currentInstanceBuffers.length = 0;
  6792. this._currentInstanceLocations.length = 0;
  6793. };
  6794. Engine.prototype._releaseBuffer = function (buffer) {
  6795. buffer.references--;
  6796. if (buffer.references === 0) {
  6797. this._gl.deleteBuffer(buffer);
  6798. return true;
  6799. }
  6800. return false;
  6801. };
  6802. Engine.prototype.createInstancesBuffer = function (capacity) {
  6803. var buffer = this._gl.createBuffer();
  6804. buffer.capacity = capacity;
  6805. this.bindArrayBuffer(buffer);
  6806. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6807. return buffer;
  6808. };
  6809. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6810. this._gl.deleteBuffer(buffer);
  6811. };
  6812. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6813. this.bindArrayBuffer(instancesBuffer);
  6814. if (data) {
  6815. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6816. }
  6817. if (offsetLocations[0].index !== undefined) {
  6818. var stride = 0;
  6819. for (var i = 0; i < offsetLocations.length; i++) {
  6820. var ai = offsetLocations[i];
  6821. stride += ai.attributeSize * 4;
  6822. }
  6823. for (var i = 0; i < offsetLocations.length; i++) {
  6824. var ai = offsetLocations[i];
  6825. this._gl.enableVertexAttribArray(ai.index);
  6826. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  6827. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  6828. this._currentInstanceLocations.push(ai.index);
  6829. this._currentInstanceBuffers.push(instancesBuffer);
  6830. }
  6831. }
  6832. else {
  6833. for (var index = 0; index < 4; index++) {
  6834. var offsetLocation = offsetLocations[index];
  6835. this._gl.enableVertexAttribArray(offsetLocation);
  6836. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6837. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6838. this._currentInstanceLocations.push(offsetLocation);
  6839. this._currentInstanceBuffers.push(instancesBuffer);
  6840. }
  6841. }
  6842. };
  6843. Engine.prototype.applyStates = function () {
  6844. this._depthCullingState.apply(this._gl);
  6845. this._alphaState.apply(this._gl);
  6846. };
  6847. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6848. // Apply states
  6849. this.applyStates();
  6850. this._drawCalls.addCount(1, false);
  6851. // Render
  6852. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6853. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6854. if (instancesCount) {
  6855. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6856. return;
  6857. }
  6858. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6859. };
  6860. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6861. // Apply states
  6862. this.applyStates();
  6863. this._drawCalls.addCount(1, false);
  6864. if (instancesCount) {
  6865. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6866. return;
  6867. }
  6868. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6869. };
  6870. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6871. // Apply states
  6872. this.applyStates();
  6873. this._drawCalls.addCount(1, false);
  6874. if (instancesCount) {
  6875. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6876. return;
  6877. }
  6878. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6879. };
  6880. // Shaders
  6881. Engine.prototype._releaseEffect = function (effect) {
  6882. if (this._compiledEffects[effect._key]) {
  6883. delete this._compiledEffects[effect._key];
  6884. if (effect.getProgram()) {
  6885. this._gl.deleteProgram(effect.getProgram());
  6886. }
  6887. }
  6888. };
  6889. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6890. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6891. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6892. var name = vertex + "+" + fragment + "@" + defines;
  6893. if (this._compiledEffects[name]) {
  6894. return this._compiledEffects[name];
  6895. }
  6896. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6897. effect._key = name;
  6898. this._compiledEffects[name] = effect;
  6899. return effect;
  6900. };
  6901. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6902. if (uniformsNames === void 0) { uniformsNames = []; }
  6903. if (samplers === void 0) { samplers = []; }
  6904. if (defines === void 0) { defines = ""; }
  6905. return this.createEffect({
  6906. vertex: "particles",
  6907. fragmentElement: fragmentName
  6908. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6909. };
  6910. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  6911. context = context || this._gl;
  6912. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  6913. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  6914. var shaderProgram = context.createProgram();
  6915. context.attachShader(shaderProgram, vertexShader);
  6916. context.attachShader(shaderProgram, fragmentShader);
  6917. context.linkProgram(shaderProgram);
  6918. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  6919. if (!linked) {
  6920. var error = context.getProgramInfoLog(shaderProgram);
  6921. if (error) {
  6922. throw new Error(error);
  6923. }
  6924. }
  6925. context.deleteShader(vertexShader);
  6926. context.deleteShader(fragmentShader);
  6927. return shaderProgram;
  6928. };
  6929. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6930. var results = [];
  6931. for (var index = 0; index < uniformsNames.length; index++) {
  6932. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6933. }
  6934. return results;
  6935. };
  6936. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6937. var results = [];
  6938. for (var index = 0; index < attributesNames.length; index++) {
  6939. try {
  6940. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6941. }
  6942. catch (e) {
  6943. results.push(-1);
  6944. }
  6945. }
  6946. return results;
  6947. };
  6948. Engine.prototype.enableEffect = function (effect) {
  6949. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6950. if (effect && effect.onBind) {
  6951. effect.onBind(effect);
  6952. }
  6953. return;
  6954. }
  6955. this._vertexAttribArraysToUse = this._vertexAttribArraysToUse || [];
  6956. this._vertexAttribArraysEnabled = this._vertexAttribArraysEnabled || [];
  6957. // Use program
  6958. this.setProgram(effect.getProgram());
  6959. var i, ul;
  6960. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6961. this._vertexAttribArraysToUse[i] = false;
  6962. }
  6963. var attributesCount = effect.getAttributesCount();
  6964. for (i = 0; i < attributesCount; i++) {
  6965. // Attributes
  6966. var order = effect.getAttributeLocation(i);
  6967. if (order >= 0) {
  6968. this._vertexAttribArraysToUse[order] = true;
  6969. }
  6970. }
  6971. for (i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  6972. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i] || this._vertexAttribArraysToUse[i]) {
  6973. continue;
  6974. }
  6975. this._vertexAttribArraysEnabled[i] = false;
  6976. this._gl.disableVertexAttribArray(i);
  6977. }
  6978. for (i = 0, ul = this._vertexAttribArraysToUse.length; i < ul; i++) {
  6979. if (this._vertexAttribArraysToUse[i] && !this._vertexAttribArraysEnabled[i]) {
  6980. this._vertexAttribArraysEnabled[i] = true;
  6981. this._gl.enableVertexAttribArray(i);
  6982. }
  6983. }
  6984. this._currentEffect = effect;
  6985. if (effect.onBind) {
  6986. effect.onBind(effect);
  6987. }
  6988. };
  6989. Engine.prototype.setIntArray = function (uniform, array) {
  6990. if (!uniform)
  6991. return;
  6992. this._gl.uniform1iv(uniform, array);
  6993. };
  6994. Engine.prototype.setIntArray2 = function (uniform, array) {
  6995. if (!uniform || array.length % 2 !== 0)
  6996. return;
  6997. this._gl.uniform2iv(uniform, array);
  6998. };
  6999. Engine.prototype.setIntArray3 = function (uniform, array) {
  7000. if (!uniform || array.length % 3 !== 0)
  7001. return;
  7002. this._gl.uniform3iv(uniform, array);
  7003. };
  7004. Engine.prototype.setIntArray4 = function (uniform, array) {
  7005. if (!uniform || array.length % 4 !== 0)
  7006. return;
  7007. this._gl.uniform4iv(uniform, array);
  7008. };
  7009. Engine.prototype.setFloatArray = function (uniform, array) {
  7010. if (!uniform)
  7011. return;
  7012. this._gl.uniform1fv(uniform, array);
  7013. };
  7014. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7015. if (!uniform || array.length % 2 !== 0)
  7016. return;
  7017. this._gl.uniform2fv(uniform, array);
  7018. };
  7019. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7020. if (!uniform || array.length % 3 !== 0)
  7021. return;
  7022. this._gl.uniform3fv(uniform, array);
  7023. };
  7024. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7025. if (!uniform || array.length % 4 !== 0)
  7026. return;
  7027. this._gl.uniform4fv(uniform, array);
  7028. };
  7029. Engine.prototype.setArray = function (uniform, array) {
  7030. if (!uniform)
  7031. return;
  7032. this._gl.uniform1fv(uniform, array);
  7033. };
  7034. Engine.prototype.setArray2 = function (uniform, array) {
  7035. if (!uniform || array.length % 2 !== 0)
  7036. return;
  7037. this._gl.uniform2fv(uniform, array);
  7038. };
  7039. Engine.prototype.setArray3 = function (uniform, array) {
  7040. if (!uniform || array.length % 3 !== 0)
  7041. return;
  7042. this._gl.uniform3fv(uniform, array);
  7043. };
  7044. Engine.prototype.setArray4 = function (uniform, array) {
  7045. if (!uniform || array.length % 4 !== 0)
  7046. return;
  7047. this._gl.uniform4fv(uniform, array);
  7048. };
  7049. Engine.prototype.setMatrices = function (uniform, matrices) {
  7050. if (!uniform)
  7051. return;
  7052. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7053. };
  7054. Engine.prototype.setMatrix = function (uniform, matrix) {
  7055. if (!uniform)
  7056. return;
  7057. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7058. };
  7059. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7060. if (!uniform)
  7061. return;
  7062. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7063. };
  7064. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7065. if (!uniform)
  7066. return;
  7067. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7068. };
  7069. Engine.prototype.setFloat = function (uniform, value) {
  7070. if (!uniform)
  7071. return;
  7072. this._gl.uniform1f(uniform, value);
  7073. };
  7074. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7075. if (!uniform)
  7076. return;
  7077. this._gl.uniform2f(uniform, x, y);
  7078. };
  7079. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7080. if (!uniform)
  7081. return;
  7082. this._gl.uniform3f(uniform, x, y, z);
  7083. };
  7084. Engine.prototype.setBool = function (uniform, bool) {
  7085. if (!uniform)
  7086. return;
  7087. this._gl.uniform1i(uniform, bool);
  7088. };
  7089. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7090. if (!uniform)
  7091. return;
  7092. this._gl.uniform4f(uniform, x, y, z, w);
  7093. };
  7094. Engine.prototype.setColor3 = function (uniform, color3) {
  7095. if (!uniform)
  7096. return;
  7097. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7098. };
  7099. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7100. if (!uniform)
  7101. return;
  7102. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7103. };
  7104. // States
  7105. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7106. if (zOffset === void 0) { zOffset = 0; }
  7107. if (reverseSide === void 0) { reverseSide = false; }
  7108. // Culling
  7109. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7110. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7111. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7112. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7113. if (culling) {
  7114. this._depthCullingState.cullFace = cullFace;
  7115. this._depthCullingState.cull = true;
  7116. }
  7117. else {
  7118. this._depthCullingState.cull = false;
  7119. }
  7120. }
  7121. // Z offset
  7122. this._depthCullingState.zOffset = zOffset;
  7123. };
  7124. Engine.prototype.setDepthBuffer = function (enable) {
  7125. this._depthCullingState.depthTest = enable;
  7126. };
  7127. Engine.prototype.getDepthWrite = function () {
  7128. return this._depthCullingState.depthMask;
  7129. };
  7130. Engine.prototype.setDepthWrite = function (enable) {
  7131. this._depthCullingState.depthMask = enable;
  7132. };
  7133. Engine.prototype.setColorWrite = function (enable) {
  7134. this._gl.colorMask(enable, enable, enable, enable);
  7135. };
  7136. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7137. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7138. if (this._alphaMode === mode) {
  7139. return;
  7140. }
  7141. switch (mode) {
  7142. case Engine.ALPHA_DISABLE:
  7143. this._alphaState.alphaBlend = false;
  7144. break;
  7145. case Engine.ALPHA_COMBINE:
  7146. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7147. this._alphaState.alphaBlend = true;
  7148. break;
  7149. case Engine.ALPHA_ONEONE:
  7150. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7151. this._alphaState.alphaBlend = true;
  7152. break;
  7153. case Engine.ALPHA_ADD:
  7154. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7155. this._alphaState.alphaBlend = true;
  7156. break;
  7157. case Engine.ALPHA_SUBTRACT:
  7158. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7159. this._alphaState.alphaBlend = true;
  7160. break;
  7161. case Engine.ALPHA_MULTIPLY:
  7162. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7163. this._alphaState.alphaBlend = true;
  7164. break;
  7165. case Engine.ALPHA_MAXIMIZED:
  7166. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7167. this._alphaState.alphaBlend = true;
  7168. break;
  7169. }
  7170. if (!noDepthWriteChange) {
  7171. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7172. }
  7173. this._alphaMode = mode;
  7174. };
  7175. Engine.prototype.getAlphaMode = function () {
  7176. return this._alphaMode;
  7177. };
  7178. Engine.prototype.setAlphaTesting = function (enable) {
  7179. this._alphaTest = enable;
  7180. };
  7181. Engine.prototype.getAlphaTesting = function () {
  7182. return this._alphaTest;
  7183. };
  7184. // Textures
  7185. Engine.prototype.wipeCaches = function () {
  7186. this.resetTextureCache();
  7187. this._currentEffect = null;
  7188. this._depthCullingState.reset();
  7189. this.setDepthFunctionToLessOrEqual();
  7190. this._alphaState.reset();
  7191. this._cachedVertexBuffers = null;
  7192. this._cachedIndexBuffer = null;
  7193. this._cachedEffectForVertexBuffers = null;
  7194. };
  7195. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7196. var gl = this._gl;
  7197. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7198. var magFilter = gl.NEAREST;
  7199. var minFilter = gl.NEAREST;
  7200. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7201. magFilter = gl.LINEAR;
  7202. minFilter = gl.LINEAR;
  7203. }
  7204. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7205. magFilter = gl.LINEAR;
  7206. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7207. }
  7208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7210. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7211. texture.samplingMode = samplingMode;
  7212. };
  7213. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7214. var _this = this;
  7215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7216. if (onLoad === void 0) { onLoad = null; }
  7217. if (onError === void 0) { onError = null; }
  7218. if (buffer === void 0) { buffer = null; }
  7219. var texture = this._gl.createTexture();
  7220. var extension;
  7221. var fromData = false;
  7222. if (url.substr(0, 5) === "data:") {
  7223. fromData = true;
  7224. }
  7225. if (!fromData)
  7226. extension = url.substr(url.length - 4, 4).toLowerCase();
  7227. else {
  7228. var oldUrl = url;
  7229. fromData = oldUrl.split(':');
  7230. url = oldUrl;
  7231. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7232. }
  7233. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7234. var isTGA = (extension === ".tga");
  7235. scene._addPendingData(texture);
  7236. texture.url = url;
  7237. texture.noMipmap = noMipmap;
  7238. texture.references = 1;
  7239. texture.samplingMode = samplingMode;
  7240. this._loadedTexturesCache.push(texture);
  7241. var onerror = function () {
  7242. scene._removePendingData(texture);
  7243. if (onError) {
  7244. onError();
  7245. }
  7246. };
  7247. var callback;
  7248. if (isTGA) {
  7249. callback = function (arrayBuffer) {
  7250. var data = new Uint8Array(arrayBuffer);
  7251. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7252. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7253. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7254. }, onLoad, samplingMode);
  7255. };
  7256. if (!(fromData instanceof Array))
  7257. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7258. callback(arrayBuffer);
  7259. }, onerror, scene.database, true);
  7260. else
  7261. callback(buffer);
  7262. }
  7263. else if (isDDS) {
  7264. callback = function (data) {
  7265. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7266. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7267. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7268. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7269. }, onLoad, samplingMode);
  7270. };
  7271. if (!(fromData instanceof Array))
  7272. BABYLON.Tools.LoadFile(url, function (data) {
  7273. callback(data);
  7274. }, onerror, scene.database, true);
  7275. else
  7276. callback(buffer);
  7277. }
  7278. else {
  7279. var onload = function (img) {
  7280. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7281. var isPot = (img.width === potWidth && img.height === potHeight);
  7282. if (!isPot) {
  7283. _this._prepareWorkingCanvas();
  7284. _this._workingCanvas.width = potWidth;
  7285. _this._workingCanvas.height = potHeight;
  7286. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7287. _this._workingContext.imageSmoothingEnabled = false;
  7288. _this._workingContext.mozImageSmoothingEnabled = false;
  7289. _this._workingContext.oImageSmoothingEnabled = false;
  7290. _this._workingContext.webkitImageSmoothingEnabled = false;
  7291. _this._workingContext.msImageSmoothingEnabled = false;
  7292. }
  7293. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7294. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7295. _this._workingContext.imageSmoothingEnabled = true;
  7296. _this._workingContext.mozImageSmoothingEnabled = true;
  7297. _this._workingContext.oImageSmoothingEnabled = true;
  7298. _this._workingContext.webkitImageSmoothingEnabled = true;
  7299. _this._workingContext.msImageSmoothingEnabled = true;
  7300. }
  7301. }
  7302. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7303. }, onLoad, samplingMode);
  7304. };
  7305. if (!(fromData instanceof Array))
  7306. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7307. else
  7308. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7309. }
  7310. return texture;
  7311. };
  7312. Engine.prototype._getInternalFormat = function (format) {
  7313. var internalFormat = this._gl.RGBA;
  7314. switch (format) {
  7315. case Engine.TEXTUREFORMAT_ALPHA:
  7316. internalFormat = this._gl.ALPHA;
  7317. break;
  7318. case Engine.TEXTUREFORMAT_LUMINANCE:
  7319. internalFormat = this._gl.LUMINANCE;
  7320. break;
  7321. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7322. internalFormat = this._gl.LUMINANCE_ALPHA;
  7323. break;
  7324. case Engine.TEXTUREFORMAT_RGB:
  7325. internalFormat = this._gl.RGB;
  7326. break;
  7327. case Engine.TEXTUREFORMAT_RGBA:
  7328. internalFormat = this._gl.RGBA;
  7329. break;
  7330. }
  7331. return internalFormat;
  7332. };
  7333. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7334. if (compression === void 0) { compression = null; }
  7335. var internalFormat = this._getInternalFormat(format);
  7336. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7337. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7338. if (texture._width % 4 !== 0) {
  7339. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7340. }
  7341. if (compression) {
  7342. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7343. }
  7344. else {
  7345. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7346. }
  7347. if (texture.generateMipMaps) {
  7348. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7349. }
  7350. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7351. this.resetTextureCache();
  7352. texture.isReady = true;
  7353. };
  7354. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7355. if (compression === void 0) { compression = null; }
  7356. var texture = this._gl.createTexture();
  7357. texture._baseWidth = width;
  7358. texture._baseHeight = height;
  7359. texture._width = width;
  7360. texture._height = height;
  7361. texture.references = 1;
  7362. this.updateRawTexture(texture, data, format, invertY, compression);
  7363. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7364. // Filters
  7365. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7366. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7368. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7369. texture.samplingMode = samplingMode;
  7370. this._loadedTexturesCache.push(texture);
  7371. return texture;
  7372. };
  7373. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7374. var texture = this._gl.createTexture();
  7375. texture._baseWidth = width;
  7376. texture._baseHeight = height;
  7377. if (generateMipMaps) {
  7378. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7379. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7380. }
  7381. this.resetTextureCache();
  7382. texture._width = width;
  7383. texture._height = height;
  7384. texture.isReady = false;
  7385. texture.generateMipMaps = generateMipMaps;
  7386. texture.references = 1;
  7387. texture.samplingMode = samplingMode;
  7388. this.updateTextureSamplingMode(samplingMode, texture);
  7389. this._loadedTexturesCache.push(texture);
  7390. return texture;
  7391. };
  7392. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7393. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7394. if (texture.isCube) {
  7395. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7396. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7397. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7398. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7399. }
  7400. else {
  7401. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7402. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7403. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7404. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7405. }
  7406. };
  7407. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7408. if (premulAlpha === void 0) { premulAlpha = false; }
  7409. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7410. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7411. if (premulAlpha) {
  7412. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7413. }
  7414. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7415. if (texture.generateMipMaps) {
  7416. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7417. }
  7418. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7419. this.resetTextureCache();
  7420. texture.isReady = true;
  7421. };
  7422. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7423. if (texture._isDisabled) {
  7424. return;
  7425. }
  7426. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7427. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7428. try {
  7429. // Testing video texture support
  7430. if (this._videoTextureSupported === undefined) {
  7431. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7432. if (this._gl.getError() !== 0) {
  7433. this._videoTextureSupported = false;
  7434. }
  7435. else {
  7436. this._videoTextureSupported = true;
  7437. }
  7438. }
  7439. // Copy video through the current working canvas if video texture is not supported
  7440. if (!this._videoTextureSupported) {
  7441. if (!texture._workingCanvas) {
  7442. texture._workingCanvas = document.createElement("canvas");
  7443. texture._workingContext = texture._workingCanvas.getContext("2d");
  7444. texture._workingCanvas.width = texture._width;
  7445. texture._workingCanvas.height = texture._height;
  7446. }
  7447. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7448. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7449. }
  7450. else {
  7451. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7452. }
  7453. if (texture.generateMipMaps) {
  7454. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7455. }
  7456. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7457. this.resetTextureCache();
  7458. texture.isReady = true;
  7459. }
  7460. catch (ex) {
  7461. // Something unexpected
  7462. // Let's disable the texture
  7463. texture._isDisabled = true;
  7464. }
  7465. };
  7466. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7467. // old version had a "generateMipMaps" arg instead of options.
  7468. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7469. // in the same way, generateDepthBuffer is defaulted to true
  7470. var generateMipMaps = false;
  7471. var generateDepthBuffer = true;
  7472. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7473. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7474. if (options !== undefined) {
  7475. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7476. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7477. type = options.type === undefined ? type : options.type;
  7478. if (options.samplingMode !== undefined) {
  7479. samplingMode = options.samplingMode;
  7480. }
  7481. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7482. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7483. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7484. }
  7485. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7486. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7487. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7488. }
  7489. }
  7490. var gl = this._gl;
  7491. var texture = gl.createTexture();
  7492. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7493. var width = size.width || size;
  7494. var height = size.height || size;
  7495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7496. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7497. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7498. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7499. }
  7500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7504. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7505. var depthBuffer;
  7506. // Create the depth buffer
  7507. if (generateDepthBuffer) {
  7508. depthBuffer = gl.createRenderbuffer();
  7509. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7510. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7511. }
  7512. // Create the framebuffer
  7513. var framebuffer = gl.createFramebuffer();
  7514. this.bindUnboundFramebuffer(framebuffer);
  7515. if (generateDepthBuffer) {
  7516. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7517. }
  7518. if (generateMipMaps) {
  7519. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7520. }
  7521. // Unbind
  7522. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7523. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7524. this.bindUnboundFramebuffer(null);
  7525. texture._framebuffer = framebuffer;
  7526. if (generateDepthBuffer) {
  7527. texture._depthBuffer = depthBuffer;
  7528. }
  7529. texture._baseWidth = width;
  7530. texture._baseHeight = height;
  7531. texture._width = width;
  7532. texture._height = height;
  7533. texture.isReady = true;
  7534. texture.generateMipMaps = generateMipMaps;
  7535. texture.references = 1;
  7536. texture.samplingMode = samplingMode;
  7537. texture.type = type;
  7538. this.resetTextureCache();
  7539. this._loadedTexturesCache.push(texture);
  7540. return texture;
  7541. };
  7542. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7543. var gl = this._gl;
  7544. var texture = gl.createTexture();
  7545. var generateMipMaps = true;
  7546. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7547. if (options !== undefined) {
  7548. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7549. if (options.samplingMode !== undefined) {
  7550. samplingMode = options.samplingMode;
  7551. }
  7552. }
  7553. texture.isCube = true;
  7554. texture.references = 1;
  7555. texture.generateMipMaps = generateMipMaps;
  7556. texture.references = 1;
  7557. texture.samplingMode = samplingMode;
  7558. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7559. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7560. for (var face = 0; face < 6; face++) {
  7561. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7562. }
  7563. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7567. // Create the depth buffer
  7568. var depthBuffer = gl.createRenderbuffer();
  7569. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  7570. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7571. // Create the framebuffer
  7572. var framebuffer = gl.createFramebuffer();
  7573. this.bindUnboundFramebuffer(framebuffer);
  7574. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  7575. // Mipmaps
  7576. if (texture.generateMipMaps) {
  7577. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7578. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7579. }
  7580. // Unbind
  7581. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7582. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7583. this.bindUnboundFramebuffer(null);
  7584. texture._framebuffer = framebuffer;
  7585. texture._depthBuffer = depthBuffer;
  7586. this.resetTextureCache();
  7587. texture._width = size;
  7588. texture._height = size;
  7589. texture.isReady = true;
  7590. return texture;
  7591. };
  7592. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7593. var _this = this;
  7594. var gl = this._gl;
  7595. var texture = gl.createTexture();
  7596. texture.isCube = true;
  7597. texture.url = rootUrl;
  7598. texture.references = 1;
  7599. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7600. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7601. if (isDDS) {
  7602. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7603. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7604. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7605. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7606. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7607. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7608. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7609. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7610. }
  7611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  7613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7615. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7616. _this.resetTextureCache();
  7617. texture._width = info.width;
  7618. texture._height = info.height;
  7619. texture.isReady = true;
  7620. }, null, null, true);
  7621. }
  7622. else {
  7623. cascadeLoad(rootUrl, scene, function (imgs) {
  7624. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  7625. var height = width;
  7626. _this._prepareWorkingCanvas();
  7627. _this._workingCanvas.width = width;
  7628. _this._workingCanvas.height = height;
  7629. var faces = [
  7630. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7631. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7632. ];
  7633. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7634. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7635. for (var index = 0; index < faces.length; index++) {
  7636. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  7637. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  7638. }
  7639. if (!noMipmap) {
  7640. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7641. }
  7642. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7643. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7646. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7647. _this.resetTextureCache();
  7648. texture._width = width;
  7649. texture._height = height;
  7650. texture.isReady = true;
  7651. }, files);
  7652. }
  7653. return texture;
  7654. };
  7655. Engine.prototype.updateTextureSize = function (texture, width, height) {
  7656. texture._width = width;
  7657. texture._height = height;
  7658. texture._size = width * height;
  7659. texture._baseWidth = width;
  7660. texture._baseHeight = height;
  7661. };
  7662. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  7663. var _this = this;
  7664. var gl = this._gl;
  7665. var texture = gl.createTexture();
  7666. scene._addPendingData(texture);
  7667. texture.isCube = true;
  7668. texture.references = 1;
  7669. texture.url = url;
  7670. var internalFormat = this._getInternalFormat(format);
  7671. var textureType = gl.UNSIGNED_BYTE;
  7672. if (type === Engine.TEXTURETYPE_FLOAT) {
  7673. textureType = gl.FLOAT;
  7674. }
  7675. var width = size;
  7676. var height = width;
  7677. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7678. texture._width = width;
  7679. texture._height = height;
  7680. var onerror = function () {
  7681. scene._removePendingData(texture);
  7682. };
  7683. var internalCallback = function (data) {
  7684. var rgbeDataArrays = callback(data);
  7685. var facesIndex = [
  7686. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  7687. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  7688. ];
  7689. width = texture._width;
  7690. height = texture._height;
  7691. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  7692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7693. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  7694. if (!noMipmap && isPot) {
  7695. if (mipmmapGenerator) {
  7696. var arrayTemp = [];
  7697. // Data are known to be in +X +Y +Z -X -Y -Z
  7698. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  7699. arrayTemp.push(rgbeDataArrays[0]); // +X
  7700. arrayTemp.push(rgbeDataArrays[3]); // -X
  7701. arrayTemp.push(rgbeDataArrays[1]); // +Y
  7702. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7703. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7704. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7705. var mipData = mipmmapGenerator(arrayTemp);
  7706. for (var level = 0; level < mipData.length; level++) {
  7707. var mipSize = width >> level;
  7708. // mipData is order in +X -X +Y -Y +Z -Z
  7709. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7710. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7711. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7712. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7713. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7714. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7715. }
  7716. }
  7717. else {
  7718. // Data are known to be in +X +Y +Z -X -Y -Z
  7719. for (var index = 0; index < facesIndex.length; index++) {
  7720. var faceData = rgbeDataArrays[index];
  7721. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7722. }
  7723. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7724. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  7725. // By following the webgl standard changes from Revision 7, 2014/11/24
  7726. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  7727. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  7728. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  7729. // Data are known to be in +X +Y +Z -X -Y -Z
  7730. for (var index = 0; index < facesIndex.length; index++) {
  7731. var faceData = rgbeDataArrays[index];
  7732. // Create a new RGBA Face.
  7733. var newFaceData = new Float32Array(width * height * 4);
  7734. for (var x = 0; x < width; x++) {
  7735. for (var y = 0; y < height; y++) {
  7736. var index_1 = (y * width + x) * 3;
  7737. var newIndex = (y * width + x) * 4;
  7738. // Map Old Value to new value.
  7739. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  7740. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  7741. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  7742. // Add fully opaque alpha channel.
  7743. newFaceData[newIndex + 3] = 1;
  7744. }
  7745. }
  7746. // Reupload the face.
  7747. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  7748. }
  7749. // Try to generate mipmap again.
  7750. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7751. }
  7752. }
  7753. }
  7754. else {
  7755. noMipmap = true;
  7756. }
  7757. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7760. }
  7761. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  7762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7764. }
  7765. else {
  7766. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7768. }
  7769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7771. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7772. texture.isReady = true;
  7773. _this.resetTextureCache();
  7774. scene._removePendingData(texture);
  7775. };
  7776. BABYLON.Tools.LoadFile(url, function (data) {
  7777. internalCallback(data);
  7778. }, onerror, scene.database, true);
  7779. return texture;
  7780. };
  7781. ;
  7782. Engine.prototype._releaseTexture = function (texture) {
  7783. var gl = this._gl;
  7784. if (texture._framebuffer) {
  7785. gl.deleteFramebuffer(texture._framebuffer);
  7786. }
  7787. if (texture._depthBuffer) {
  7788. gl.deleteRenderbuffer(texture._depthBuffer);
  7789. }
  7790. gl.deleteTexture(texture);
  7791. // Unbind channels
  7792. this.unbindAllTextures();
  7793. var index = this._loadedTexturesCache.indexOf(texture);
  7794. if (index !== -1) {
  7795. this._loadedTexturesCache.splice(index, 1);
  7796. }
  7797. };
  7798. Engine.prototype.setProgram = function (program) {
  7799. if (this._currentProgram !== program) {
  7800. this._gl.useProgram(program);
  7801. this._currentProgram = program;
  7802. }
  7803. };
  7804. Engine.prototype.bindSamplers = function (effect) {
  7805. this.setProgram(effect.getProgram());
  7806. var samplers = effect.getSamplers();
  7807. for (var index = 0; index < samplers.length; index++) {
  7808. var uniform = effect.getUniform(samplers[index]);
  7809. this._gl.uniform1i(uniform, index);
  7810. }
  7811. this._currentEffect = null;
  7812. };
  7813. Engine.prototype.activateTexture = function (texture) {
  7814. if (this._activeTexture !== texture) {
  7815. this._gl.activeTexture(texture);
  7816. this._activeTexture = texture;
  7817. }
  7818. };
  7819. Engine.prototype._bindTextureDirectly = function (target, texture) {
  7820. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  7821. this._gl.bindTexture(target, texture);
  7822. this._activeTexturesCache[this._activeTexture] = texture;
  7823. }
  7824. };
  7825. Engine.prototype._bindTexture = function (channel, texture) {
  7826. if (channel < 0) {
  7827. return;
  7828. }
  7829. this.activateTexture(this._gl["TEXTURE" + channel]);
  7830. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7831. };
  7832. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7833. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7834. };
  7835. Engine.prototype.unbindAllTextures = function () {
  7836. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7837. this.activateTexture(this._gl["TEXTURE" + channel]);
  7838. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7839. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7840. }
  7841. };
  7842. Engine.prototype.setTexture = function (channel, uniform, texture) {
  7843. if (channel < 0) {
  7844. return;
  7845. }
  7846. this._gl.uniform1i(uniform, channel);
  7847. this._setTexture(channel, texture);
  7848. };
  7849. Engine.prototype._setTexture = function (channel, texture) {
  7850. // Not ready?
  7851. if (!texture || !texture.isReady()) {
  7852. if (this._activeTexturesCache[channel] != null) {
  7853. this.activateTexture(this._gl["TEXTURE" + channel]);
  7854. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7855. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7856. }
  7857. return;
  7858. }
  7859. // Video
  7860. var alreadyActivated = false;
  7861. if (texture instanceof BABYLON.VideoTexture) {
  7862. this.activateTexture(this._gl["TEXTURE" + channel]);
  7863. alreadyActivated = true;
  7864. texture.update();
  7865. }
  7866. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7867. texture.delayLoad();
  7868. return;
  7869. }
  7870. var internalTexture = texture.getInternalTexture();
  7871. if (this._activeTexturesCache[channel] === internalTexture) {
  7872. return;
  7873. }
  7874. if (!alreadyActivated) {
  7875. this.activateTexture(this._gl["TEXTURE" + channel]);
  7876. }
  7877. if (internalTexture.isCube) {
  7878. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7879. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7880. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7881. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7882. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7883. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7884. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7885. }
  7886. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7887. }
  7888. else {
  7889. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  7890. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7891. internalTexture._cachedWrapU = texture.wrapU;
  7892. switch (texture.wrapU) {
  7893. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7894. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7895. break;
  7896. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7898. break;
  7899. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7900. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7901. break;
  7902. }
  7903. }
  7904. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7905. internalTexture._cachedWrapV = texture.wrapV;
  7906. switch (texture.wrapV) {
  7907. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7908. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7909. break;
  7910. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7912. break;
  7913. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7914. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7915. break;
  7916. }
  7917. }
  7918. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7919. }
  7920. };
  7921. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  7922. if (channel < 0) {
  7923. return;
  7924. }
  7925. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  7926. this._textureUnits = new Int32Array(textures.length);
  7927. }
  7928. for (var i = 0; i < textures.length; i++) {
  7929. this._textureUnits[i] = channel + i;
  7930. }
  7931. this._gl.uniform1iv(uniform, this._textureUnits);
  7932. for (var index = 0; index < textures.length; index++) {
  7933. this._setTexture(channel + index, textures[index]);
  7934. }
  7935. };
  7936. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7937. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7938. var value = texture.anisotropicFilteringLevel;
  7939. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7940. value = 1;
  7941. }
  7942. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7943. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7944. texture._cachedAnisotropicFilteringLevel = value;
  7945. }
  7946. };
  7947. Engine.prototype.readPixels = function (x, y, width, height) {
  7948. var data = new Uint8Array(height * width * 4);
  7949. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7950. return data;
  7951. };
  7952. /**
  7953. * Add an externaly attached data from its key.
  7954. * This method call will fail and return false, if such key already exists.
  7955. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  7956. * @param key the unique key that identifies the data
  7957. * @param data the data object to associate to the key for this Engine instance
  7958. * @return true if no such key were already present and the data was added successfully, false otherwise
  7959. */
  7960. Engine.prototype.addExternalData = function (key, data) {
  7961. return this._externalData.add(key, data);
  7962. };
  7963. /**
  7964. * Get an externaly attached data from its key
  7965. * @param key the unique key that identifies the data
  7966. * @return the associated data, if present (can be null), or undefined if not present
  7967. */
  7968. Engine.prototype.getExternalData = function (key) {
  7969. return this._externalData.get(key);
  7970. };
  7971. /**
  7972. * Get an externaly attached data from its key, create it using a factory if it's not already present
  7973. * @param key the unique key that identifies the data
  7974. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  7975. * @return the associated data, can be null if the factory returned null.
  7976. */
  7977. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  7978. return this._externalData.getOrAddWithFactory(key, factory);
  7979. };
  7980. /**
  7981. * Remove an externaly attached data from the Engine instance
  7982. * @param key the unique key that identifies the data
  7983. * @return true if the data was successfully removed, false if it doesn't exist
  7984. */
  7985. Engine.prototype.removeExternalData = function (key) {
  7986. return this._externalData.remove(key);
  7987. };
  7988. Engine.prototype.releaseInternalTexture = function (texture) {
  7989. if (!texture) {
  7990. return;
  7991. }
  7992. texture.references--;
  7993. // Final reference ?
  7994. if (texture.references === 0) {
  7995. var texturesCache = this.getLoadedTexturesCache();
  7996. var index = texturesCache.indexOf(texture);
  7997. if (index > -1) {
  7998. texturesCache.splice(index, 1);
  7999. }
  8000. this._releaseTexture(texture);
  8001. }
  8002. };
  8003. // Dispose
  8004. Engine.prototype.dispose = function () {
  8005. this.hideLoadingUI();
  8006. this.stopRenderLoop();
  8007. // Release scenes
  8008. while (this.scenes.length) {
  8009. this.scenes[0].dispose();
  8010. }
  8011. // Release audio engine
  8012. Engine.audioEngine.dispose();
  8013. // Release effects
  8014. for (var name in this._compiledEffects) {
  8015. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8016. }
  8017. // Unbind
  8018. if (this._vertexAttribArraysEnabled) {
  8019. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8020. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArraysEnabled[i]) {
  8021. continue;
  8022. }
  8023. this._gl.disableVertexAttribArray(i);
  8024. }
  8025. }
  8026. this._gl = null;
  8027. // Events
  8028. window.removeEventListener("blur", this._onBlur);
  8029. window.removeEventListener("focus", this._onFocus);
  8030. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8031. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8032. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8033. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8034. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8035. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8036. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8037. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8038. };
  8039. // Loading screen
  8040. Engine.prototype.displayLoadingUI = function () {
  8041. this._loadingScreen.displayLoadingUI();
  8042. };
  8043. Engine.prototype.hideLoadingUI = function () {
  8044. this._loadingScreen.hideLoadingUI();
  8045. };
  8046. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8047. get: function () {
  8048. return this._loadingScreen;
  8049. },
  8050. set: function (loadingScreen) {
  8051. this._loadingScreen = loadingScreen;
  8052. },
  8053. enumerable: true,
  8054. configurable: true
  8055. });
  8056. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8057. set: function (text) {
  8058. this._loadingScreen.loadingUIText = text;
  8059. },
  8060. enumerable: true,
  8061. configurable: true
  8062. });
  8063. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8064. set: function (color) {
  8065. this._loadingScreen.loadingUIBackgroundColor = color;
  8066. },
  8067. enumerable: true,
  8068. configurable: true
  8069. });
  8070. Engine.prototype.attachContextLostEvent = function (callback) {
  8071. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8072. };
  8073. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8074. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8075. };
  8076. // FPS
  8077. Engine.prototype.getFps = function () {
  8078. return this.fps;
  8079. };
  8080. Engine.prototype.getDeltaTime = function () {
  8081. return this.deltaTime;
  8082. };
  8083. Engine.prototype._measureFps = function () {
  8084. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8085. var length = this.previousFramesDuration.length;
  8086. if (length >= 2) {
  8087. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8088. }
  8089. if (length >= this.fpsRange) {
  8090. if (length > this.fpsRange) {
  8091. this.previousFramesDuration.splice(0, 1);
  8092. length = this.previousFramesDuration.length;
  8093. }
  8094. var sum = 0;
  8095. for (var id = 0; id < length - 1; id++) {
  8096. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8097. }
  8098. this.fps = 1000.0 / (sum / (length - 1));
  8099. }
  8100. };
  8101. Engine.prototype._canRenderToFloatTexture = function () {
  8102. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8103. };
  8104. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8105. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8106. };
  8107. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8108. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8109. var tempcanvas = document.createElement("canvas");
  8110. tempcanvas.height = 16;
  8111. tempcanvas.width = 16;
  8112. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8113. // extension.
  8114. var ext = gl.getExtension(extension);
  8115. if (!ext) {
  8116. return false;
  8117. }
  8118. // setup GLSL program
  8119. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8120. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  8121. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8122. gl.useProgram(program);
  8123. // look up where the vertex data needs to go.
  8124. var positionLocation = gl.getAttribLocation(program, "a_position");
  8125. var colorLoc = gl.getUniformLocation(program, "u_color");
  8126. // provide texture coordinates for the rectangle.
  8127. var positionBuffer = gl.createBuffer();
  8128. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8129. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8130. -1.0, -1.0,
  8131. 1.0, -1.0,
  8132. -1.0, 1.0,
  8133. -1.0, 1.0,
  8134. 1.0, -1.0,
  8135. 1.0, 1.0]), gl.STATIC_DRAW);
  8136. gl.enableVertexAttribArray(positionLocation);
  8137. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8138. var whiteTex = gl.createTexture();
  8139. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8140. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8141. var tex = gl.createTexture();
  8142. gl.bindTexture(gl.TEXTURE_2D, tex);
  8143. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8145. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8146. var fb = gl.createFramebuffer();
  8147. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8149. var cleanup = function () {
  8150. gl.deleteProgram(program);
  8151. gl.disableVertexAttribArray(positionLocation);
  8152. gl.deleteBuffer(positionBuffer);
  8153. gl.deleteFramebuffer(fb);
  8154. gl.deleteTexture(whiteTex);
  8155. gl.deleteTexture(tex);
  8156. };
  8157. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8158. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8159. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8160. cleanup();
  8161. return false;
  8162. }
  8163. // Draw the rectangle.
  8164. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8165. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8166. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8167. gl.bindTexture(gl.TEXTURE_2D, tex);
  8168. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8169. gl.clearColor(1, 0, 0, 1);
  8170. gl.clear(gl.COLOR_BUFFER_BIT);
  8171. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8172. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8173. var pixel = new Uint8Array(4);
  8174. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8175. if (pixel[0] !== 0 ||
  8176. pixel[1] < 248 ||
  8177. pixel[2] < 248 ||
  8178. pixel[3] < 254) {
  8179. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8180. cleanup();
  8181. return false;
  8182. }
  8183. // Succesfully rendered to "format" texture.
  8184. cleanup();
  8185. return true;
  8186. };
  8187. // Statics
  8188. Engine.isSupported = function () {
  8189. try {
  8190. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8191. if (navigator.isCocoonJS) {
  8192. return true;
  8193. }
  8194. var tempcanvas = document.createElement("canvas");
  8195. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8196. return gl != null && !!window.WebGLRenderingContext;
  8197. }
  8198. catch (e) {
  8199. return false;
  8200. }
  8201. };
  8202. // Const statics
  8203. Engine._ALPHA_DISABLE = 0;
  8204. Engine._ALPHA_ADD = 1;
  8205. Engine._ALPHA_COMBINE = 2;
  8206. Engine._ALPHA_SUBTRACT = 3;
  8207. Engine._ALPHA_MULTIPLY = 4;
  8208. Engine._ALPHA_MAXIMIZED = 5;
  8209. Engine._ALPHA_ONEONE = 6;
  8210. Engine._DELAYLOADSTATE_NONE = 0;
  8211. Engine._DELAYLOADSTATE_LOADED = 1;
  8212. Engine._DELAYLOADSTATE_LOADING = 2;
  8213. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8214. Engine._TEXTUREFORMAT_ALPHA = 0;
  8215. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8216. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8217. Engine._TEXTUREFORMAT_RGB = 4;
  8218. Engine._TEXTUREFORMAT_RGBA = 5;
  8219. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8220. Engine._TEXTURETYPE_FLOAT = 1;
  8221. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8222. // Updatable statics so stick with vars here
  8223. Engine.CollisionsEpsilon = 0.001;
  8224. Engine.CodeRepository = "src/";
  8225. Engine.ShadersRepository = "src/Shaders/";
  8226. return Engine;
  8227. })();
  8228. BABYLON.Engine = Engine;
  8229. })(BABYLON || (BABYLON = {}));
  8230. var BABYLON;
  8231. (function (BABYLON) {
  8232. /**
  8233. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8234. */
  8235. var Node = (function () {
  8236. /**
  8237. * @constructor
  8238. * @param {string} name - the name and id to be given to this node
  8239. * @param {BABYLON.Scene} the scene this node will be added to
  8240. */
  8241. function Node(name, scene) {
  8242. this.state = "";
  8243. this.animations = new Array();
  8244. this._ranges = {};
  8245. this._childrenFlag = -1;
  8246. this._isEnabled = true;
  8247. this._isReady = true;
  8248. this._currentRenderId = -1;
  8249. this._parentRenderId = -1;
  8250. this.name = name;
  8251. this.id = name;
  8252. this._scene = scene;
  8253. this._initCache();
  8254. }
  8255. Object.defineProperty(Node.prototype, "parent", {
  8256. get: function () {
  8257. return this._parentNode;
  8258. },
  8259. set: function (parent) {
  8260. if (this._parentNode === parent) {
  8261. return;
  8262. }
  8263. if (this._parentNode) {
  8264. var index = this._parentNode._children.indexOf(this);
  8265. if (index !== -1) {
  8266. this._parentNode._children.splice(index, 1);
  8267. }
  8268. }
  8269. this._parentNode = parent;
  8270. if (this._parentNode) {
  8271. if (!this._parentNode._children) {
  8272. this._parentNode._children = new Array();
  8273. }
  8274. this._parentNode._children.push(this);
  8275. }
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. Node.prototype.getScene = function () {
  8281. return this._scene;
  8282. };
  8283. Node.prototype.getEngine = function () {
  8284. return this._scene.getEngine();
  8285. };
  8286. // override it in derived class
  8287. Node.prototype.getWorldMatrix = function () {
  8288. return BABYLON.Matrix.Identity();
  8289. };
  8290. // override it in derived class if you add new variables to the cache
  8291. // and call the parent class method
  8292. Node.prototype._initCache = function () {
  8293. this._cache = {};
  8294. this._cache.parent = undefined;
  8295. };
  8296. Node.prototype.updateCache = function (force) {
  8297. if (!force && this.isSynchronized())
  8298. return;
  8299. this._cache.parent = this.parent;
  8300. this._updateCache();
  8301. };
  8302. // override it in derived class if you add new variables to the cache
  8303. // and call the parent class method if !ignoreParentClass
  8304. Node.prototype._updateCache = function (ignoreParentClass) {
  8305. };
  8306. // override it in derived class if you add new variables to the cache
  8307. Node.prototype._isSynchronized = function () {
  8308. return true;
  8309. };
  8310. Node.prototype._markSyncedWithParent = function () {
  8311. this._parentRenderId = this.parent._currentRenderId;
  8312. };
  8313. Node.prototype.isSynchronizedWithParent = function () {
  8314. if (!this.parent) {
  8315. return true;
  8316. }
  8317. if (this._parentRenderId !== this.parent._currentRenderId) {
  8318. return false;
  8319. }
  8320. return this.parent.isSynchronized();
  8321. };
  8322. Node.prototype.isSynchronized = function (updateCache) {
  8323. var check = this.hasNewParent();
  8324. check = check || !this.isSynchronizedWithParent();
  8325. check = check || !this._isSynchronized();
  8326. if (updateCache)
  8327. this.updateCache(true);
  8328. return !check;
  8329. };
  8330. Node.prototype.hasNewParent = function (update) {
  8331. if (this._cache.parent === this.parent)
  8332. return false;
  8333. if (update)
  8334. this._cache.parent = this.parent;
  8335. return true;
  8336. };
  8337. /**
  8338. * Is this node ready to be used/rendered
  8339. * @return {boolean} is it ready
  8340. */
  8341. Node.prototype.isReady = function () {
  8342. return this._isReady;
  8343. };
  8344. /**
  8345. * Is this node enabled.
  8346. * If the node has a parent and is enabled, the parent will be inspected as well.
  8347. * @return {boolean} whether this node (and its parent) is enabled.
  8348. * @see setEnabled
  8349. */
  8350. Node.prototype.isEnabled = function () {
  8351. if (!this._isEnabled) {
  8352. return false;
  8353. }
  8354. if (this.parent) {
  8355. return this.parent.isEnabled();
  8356. }
  8357. return true;
  8358. };
  8359. /**
  8360. * Set the enabled state of this node.
  8361. * @param {boolean} value - the new enabled state
  8362. * @see isEnabled
  8363. */
  8364. Node.prototype.setEnabled = function (value) {
  8365. this._isEnabled = value;
  8366. };
  8367. /**
  8368. * Is this node a descendant of the given node.
  8369. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8370. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8371. * @see parent
  8372. */
  8373. Node.prototype.isDescendantOf = function (ancestor) {
  8374. if (this.parent) {
  8375. if (this.parent === ancestor) {
  8376. return true;
  8377. }
  8378. return this.parent.isDescendantOf(ancestor);
  8379. }
  8380. return false;
  8381. };
  8382. /**
  8383. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8384. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8385. * @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.
  8386. * @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.
  8387. */
  8388. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8389. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8390. if (!this._children) {
  8391. return;
  8392. }
  8393. for (var index = 0; index < this._children.length; index++) {
  8394. var item = this._children[index];
  8395. if (!predicate || predicate(item)) {
  8396. results.push(item);
  8397. }
  8398. if (!directDescendantsOnly) {
  8399. item._getDescendants(results, false, predicate);
  8400. }
  8401. }
  8402. };
  8403. /**
  8404. * Will return all nodes that have this node as ascendant.
  8405. * @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.
  8406. * @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.
  8407. * @return {BABYLON.Node[]} all children nodes of all types.
  8408. */
  8409. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8410. var results = [];
  8411. this._getDescendants(results, directDescendantsOnly, predicate);
  8412. return results;
  8413. };
  8414. /**
  8415. * @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.
  8416. * @Deprecated, legacy support.
  8417. * use getDecendants instead.
  8418. */
  8419. Node.prototype.getChildren = function (predicate) {
  8420. return this.getDescendants(true, predicate);
  8421. };
  8422. /**
  8423. * Get all child-meshes of this node.
  8424. */
  8425. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8426. var results = [];
  8427. this._getDescendants(results, directDecendantsOnly, function (node) {
  8428. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8429. });
  8430. return results;
  8431. };
  8432. Node.prototype._setReady = function (state) {
  8433. if (state === this._isReady) {
  8434. return;
  8435. }
  8436. if (!state) {
  8437. this._isReady = false;
  8438. return;
  8439. }
  8440. this._isReady = true;
  8441. if (this.onReady) {
  8442. this.onReady(this);
  8443. }
  8444. };
  8445. Node.prototype.getAnimationByName = function (name) {
  8446. for (var i = 0; i < this.animations.length; i++) {
  8447. var animation = this.animations[i];
  8448. if (animation.name === name) {
  8449. return animation;
  8450. }
  8451. }
  8452. return null;
  8453. };
  8454. Node.prototype.createAnimationRange = function (name, from, to) {
  8455. // check name not already in use
  8456. if (!this._ranges[name]) {
  8457. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8458. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8459. if (this.animations[i]) {
  8460. this.animations[i].createRange(name, from, to);
  8461. }
  8462. }
  8463. }
  8464. };
  8465. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8466. if (deleteFrames === void 0) { deleteFrames = true; }
  8467. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8468. if (this.animations[i]) {
  8469. this.animations[i].deleteRange(name, deleteFrames);
  8470. }
  8471. }
  8472. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8473. };
  8474. Node.prototype.getAnimationRange = function (name) {
  8475. return this._ranges[name];
  8476. };
  8477. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8478. var range = this.getAnimationRange(name);
  8479. if (!range) {
  8480. return null;
  8481. }
  8482. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8483. };
  8484. Node.prototype.serializeAnimationRanges = function () {
  8485. var serializationRanges = [];
  8486. for (var name in this._ranges) {
  8487. var range = {};
  8488. range.name = name;
  8489. range.from = this._ranges[name].from;
  8490. range.to = this._ranges[name].to;
  8491. serializationRanges.push(range);
  8492. }
  8493. return serializationRanges;
  8494. };
  8495. Node.prototype.dispose = function () {
  8496. this.parent = null;
  8497. };
  8498. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8499. if (parsedNode.ranges) {
  8500. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8501. var data = parsedNode.ranges[index];
  8502. node.createAnimationRange(data.name, data.from, data.to);
  8503. }
  8504. }
  8505. };
  8506. __decorate([
  8507. BABYLON.serialize()
  8508. ], Node.prototype, "name", void 0);
  8509. __decorate([
  8510. BABYLON.serialize()
  8511. ], Node.prototype, "id", void 0);
  8512. __decorate([
  8513. BABYLON.serialize()
  8514. ], Node.prototype, "uniqueId", void 0);
  8515. __decorate([
  8516. BABYLON.serialize()
  8517. ], Node.prototype, "state", void 0);
  8518. return Node;
  8519. })();
  8520. BABYLON.Node = Node;
  8521. })(BABYLON || (BABYLON = {}));
  8522. var BABYLON;
  8523. (function (BABYLON) {
  8524. var FilesInput = (function () {
  8525. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8526. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8527. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8528. this._engine = p_engine;
  8529. this._canvas = p_canvas;
  8530. this._currentScene = p_scene;
  8531. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8532. this._progressCallback = p_progressCallback;
  8533. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8534. this._textureLoadingCallback = p_textureLoadingCallback;
  8535. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8536. }
  8537. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8538. var _this = this;
  8539. if (p_elementToMonitor) {
  8540. this._elementToMonitor = p_elementToMonitor;
  8541. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8542. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8543. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8544. }
  8545. };
  8546. FilesInput.prototype.renderFunction = function () {
  8547. if (this._additionnalRenderLoopLogicCallback) {
  8548. this._additionnalRenderLoopLogicCallback();
  8549. }
  8550. if (this._currentScene) {
  8551. if (this._textureLoadingCallback) {
  8552. var remaining = this._currentScene.getWaitingItemsCount();
  8553. if (remaining > 0) {
  8554. this._textureLoadingCallback(remaining);
  8555. }
  8556. }
  8557. this._currentScene.render();
  8558. }
  8559. };
  8560. FilesInput.prototype.drag = function (e) {
  8561. e.stopPropagation();
  8562. e.preventDefault();
  8563. };
  8564. FilesInput.prototype.drop = function (eventDrop) {
  8565. eventDrop.stopPropagation();
  8566. eventDrop.preventDefault();
  8567. this.loadFiles(eventDrop);
  8568. };
  8569. FilesInput.prototype.loadFiles = function (event) {
  8570. if (this._startingProcessingFilesCallback)
  8571. this._startingProcessingFilesCallback();
  8572. // Handling data transfer via drag'n'drop
  8573. if (event && event.dataTransfer && event.dataTransfer.files) {
  8574. this._filesToLoad = event.dataTransfer.files;
  8575. }
  8576. // Handling files from input files
  8577. if (event && event.target && event.target.files) {
  8578. this._filesToLoad = event.target.files;
  8579. }
  8580. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8581. for (var i = 0; i < this._filesToLoad.length; i++) {
  8582. switch (this._filesToLoad[i].type) {
  8583. case "image/jpeg":
  8584. case "image/png":
  8585. case "image/bmp":
  8586. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8587. break;
  8588. case "image/targa":
  8589. case "image/vnd.ms-dds":
  8590. case "audio/wav":
  8591. case "audio/x-wav":
  8592. case "audio/mp3":
  8593. case "audio/mpeg":
  8594. case "audio/mpeg3":
  8595. case "audio/x-mpeg-3":
  8596. case "audio/ogg":
  8597. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8598. break;
  8599. default:
  8600. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8601. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8602. }
  8603. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8604. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8605. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8606. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8607. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8608. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8609. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  8610. this._sceneFileToLoad = this._filesToLoad[i];
  8611. }
  8612. break;
  8613. }
  8614. }
  8615. this.reload();
  8616. }
  8617. };
  8618. FilesInput.prototype.reload = function () {
  8619. var _this = this;
  8620. var that = this;
  8621. // If a ".babylon" file has been provided
  8622. if (this._sceneFileToLoad) {
  8623. if (this._currentScene) {
  8624. if (BABYLON.Tools.errorsCount > 0) {
  8625. BABYLON.Tools.ClearLogCache();
  8626. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  8627. }
  8628. this._engine.stopRenderLoop();
  8629. this._currentScene.dispose();
  8630. }
  8631. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  8632. that._currentScene = newScene;
  8633. // Wait for textures and shaders to be ready
  8634. that._currentScene.executeWhenReady(function () {
  8635. // Attach camera to canvas inputs
  8636. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  8637. that._currentScene.createDefaultCameraOrLight();
  8638. }
  8639. that._currentScene.activeCamera.attachControl(that._canvas);
  8640. if (that._sceneLoadedCallback) {
  8641. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  8642. }
  8643. that._engine.runRenderLoop(function () { that.renderFunction(); });
  8644. });
  8645. }, function (progress) {
  8646. if (_this._progressCallback) {
  8647. _this._progressCallback(progress);
  8648. }
  8649. });
  8650. }
  8651. else {
  8652. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  8653. }
  8654. };
  8655. FilesInput.FilesTextures = new Array();
  8656. FilesInput.FilesToLoad = new Array();
  8657. return FilesInput;
  8658. })();
  8659. BABYLON.FilesInput = FilesInput;
  8660. })(BABYLON || (BABYLON = {}));
  8661. var BABYLON;
  8662. (function (BABYLON) {
  8663. var IntersectionInfo = (function () {
  8664. function IntersectionInfo(bu, bv, distance) {
  8665. this.bu = bu;
  8666. this.bv = bv;
  8667. this.distance = distance;
  8668. this.faceId = 0;
  8669. this.subMeshId = 0;
  8670. }
  8671. return IntersectionInfo;
  8672. })();
  8673. BABYLON.IntersectionInfo = IntersectionInfo;
  8674. var PickingInfo = (function () {
  8675. function PickingInfo() {
  8676. this.hit = false;
  8677. this.distance = 0;
  8678. this.pickedPoint = null;
  8679. this.pickedMesh = null;
  8680. this.bu = 0;
  8681. this.bv = 0;
  8682. this.faceId = -1;
  8683. this.subMeshId = 0;
  8684. this.pickedSprite = null;
  8685. }
  8686. // Methods
  8687. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  8688. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  8689. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  8690. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  8691. return null;
  8692. }
  8693. var indices = this.pickedMesh.getIndices();
  8694. var result;
  8695. if (useVerticesNormals) {
  8696. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  8697. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  8698. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  8699. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  8700. normal0 = normal0.scale(this.bu);
  8701. normal1 = normal1.scale(this.bv);
  8702. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  8703. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  8704. }
  8705. else {
  8706. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  8707. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  8708. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  8709. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  8710. var p1p2 = vertex1.subtract(vertex2);
  8711. var p3p2 = vertex3.subtract(vertex2);
  8712. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  8713. }
  8714. if (useWorldCoordinates) {
  8715. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  8716. }
  8717. return BABYLON.Vector3.Normalize(result);
  8718. };
  8719. PickingInfo.prototype.getTextureCoordinates = function () {
  8720. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8721. return null;
  8722. }
  8723. var indices = this.pickedMesh.getIndices();
  8724. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  8725. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  8726. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  8727. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  8728. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  8729. uv1 = uv1.scale(this.bu);
  8730. uv2 = uv2.scale(this.bv);
  8731. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  8732. };
  8733. return PickingInfo;
  8734. })();
  8735. BABYLON.PickingInfo = PickingInfo;
  8736. })(BABYLON || (BABYLON = {}));
  8737. var BABYLON;
  8738. (function (BABYLON) {
  8739. var BoundingSphere = (function () {
  8740. function BoundingSphere(minimum, maximum) {
  8741. this.minimum = minimum;
  8742. this.maximum = maximum;
  8743. this._tempRadiusVector = BABYLON.Vector3.Zero();
  8744. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  8745. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  8746. this.radius = distance * 0.5;
  8747. this.centerWorld = BABYLON.Vector3.Zero();
  8748. this._update(BABYLON.Matrix.Identity());
  8749. }
  8750. // Methods
  8751. BoundingSphere.prototype._update = function (world) {
  8752. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  8753. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  8754. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  8755. };
  8756. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  8757. for (var i = 0; i < 6; i++) {
  8758. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  8759. return false;
  8760. }
  8761. return true;
  8762. };
  8763. BoundingSphere.prototype.intersectsPoint = function (point) {
  8764. var x = this.centerWorld.x - point.x;
  8765. var y = this.centerWorld.y - point.y;
  8766. var z = this.centerWorld.z - point.z;
  8767. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8768. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  8769. return false;
  8770. return true;
  8771. };
  8772. // Statics
  8773. BoundingSphere.Intersects = function (sphere0, sphere1) {
  8774. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  8775. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  8776. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  8777. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  8778. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  8779. return false;
  8780. return true;
  8781. };
  8782. return BoundingSphere;
  8783. })();
  8784. BABYLON.BoundingSphere = BoundingSphere;
  8785. })(BABYLON || (BABYLON = {}));
  8786. var BABYLON;
  8787. (function (BABYLON) {
  8788. var BoundingBox = (function () {
  8789. function BoundingBox(minimum, maximum) {
  8790. this.minimum = minimum;
  8791. this.maximum = maximum;
  8792. this.vectors = new Array();
  8793. this.vectorsWorld = new Array();
  8794. // Bounding vectors
  8795. this.vectors.push(this.minimum.clone());
  8796. this.vectors.push(this.maximum.clone());
  8797. this.vectors.push(this.minimum.clone());
  8798. this.vectors[2].x = this.maximum.x;
  8799. this.vectors.push(this.minimum.clone());
  8800. this.vectors[3].y = this.maximum.y;
  8801. this.vectors.push(this.minimum.clone());
  8802. this.vectors[4].z = this.maximum.z;
  8803. this.vectors.push(this.maximum.clone());
  8804. this.vectors[5].z = this.minimum.z;
  8805. this.vectors.push(this.maximum.clone());
  8806. this.vectors[6].x = this.minimum.x;
  8807. this.vectors.push(this.maximum.clone());
  8808. this.vectors[7].y = this.minimum.y;
  8809. // OBB
  8810. this.center = this.maximum.add(this.minimum).scale(0.5);
  8811. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  8812. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  8813. // World
  8814. for (var index = 0; index < this.vectors.length; index++) {
  8815. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  8816. }
  8817. this.minimumWorld = BABYLON.Vector3.Zero();
  8818. this.maximumWorld = BABYLON.Vector3.Zero();
  8819. this._update(BABYLON.Matrix.Identity());
  8820. }
  8821. // Methods
  8822. BoundingBox.prototype.getWorldMatrix = function () {
  8823. return this._worldMatrix;
  8824. };
  8825. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  8826. this._worldMatrix.copyFrom(matrix);
  8827. return this;
  8828. };
  8829. BoundingBox.prototype._update = function (world) {
  8830. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  8831. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  8832. for (var index = 0; index < this.vectors.length; index++) {
  8833. var v = this.vectorsWorld[index];
  8834. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  8835. if (v.x < this.minimumWorld.x)
  8836. this.minimumWorld.x = v.x;
  8837. if (v.y < this.minimumWorld.y)
  8838. this.minimumWorld.y = v.y;
  8839. if (v.z < this.minimumWorld.z)
  8840. this.minimumWorld.z = v.z;
  8841. if (v.x > this.maximumWorld.x)
  8842. this.maximumWorld.x = v.x;
  8843. if (v.y > this.maximumWorld.y)
  8844. this.maximumWorld.y = v.y;
  8845. if (v.z > this.maximumWorld.z)
  8846. this.maximumWorld.z = v.z;
  8847. }
  8848. // OBB
  8849. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  8850. this.center.scaleInPlace(0.5);
  8851. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  8852. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  8853. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  8854. this._worldMatrix = world;
  8855. };
  8856. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  8857. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  8858. };
  8859. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8860. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  8861. };
  8862. BoundingBox.prototype.intersectsPoint = function (point) {
  8863. var delta = -BABYLON.Epsilon;
  8864. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  8865. return false;
  8866. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  8867. return false;
  8868. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  8869. return false;
  8870. return true;
  8871. };
  8872. BoundingBox.prototype.intersectsSphere = function (sphere) {
  8873. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  8874. };
  8875. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  8876. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  8877. return false;
  8878. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  8879. return false;
  8880. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  8881. return false;
  8882. return true;
  8883. };
  8884. // Statics
  8885. BoundingBox.Intersects = function (box0, box1) {
  8886. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  8887. return false;
  8888. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  8889. return false;
  8890. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  8891. return false;
  8892. return true;
  8893. };
  8894. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  8895. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  8896. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  8897. return (num <= (sphereRadius * sphereRadius));
  8898. };
  8899. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8900. for (var p = 0; p < 6; p++) {
  8901. for (var i = 0; i < 8; i++) {
  8902. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8903. return false;
  8904. }
  8905. }
  8906. }
  8907. return true;
  8908. };
  8909. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8910. for (var p = 0; p < 6; p++) {
  8911. var inCount = 8;
  8912. for (var i = 0; i < 8; i++) {
  8913. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8914. --inCount;
  8915. }
  8916. else {
  8917. break;
  8918. }
  8919. }
  8920. if (inCount === 0)
  8921. return false;
  8922. }
  8923. return true;
  8924. };
  8925. return BoundingBox;
  8926. })();
  8927. BABYLON.BoundingBox = BoundingBox;
  8928. })(BABYLON || (BABYLON = {}));
  8929. var BABYLON;
  8930. (function (BABYLON) {
  8931. var computeBoxExtents = function (axis, box) {
  8932. var p = BABYLON.Vector3.Dot(box.center, axis);
  8933. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8934. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8935. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8936. var r = r0 + r1 + r2;
  8937. return {
  8938. min: p - r,
  8939. max: p + r
  8940. };
  8941. };
  8942. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8943. var axisOverlap = function (axis, box0, box1) {
  8944. var result0 = computeBoxExtents(axis, box0);
  8945. var result1 = computeBoxExtents(axis, box1);
  8946. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8947. };
  8948. var BoundingInfo = (function () {
  8949. function BoundingInfo(minimum, maximum) {
  8950. this.minimum = minimum;
  8951. this.maximum = maximum;
  8952. this._isLocked = false;
  8953. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8954. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8955. }
  8956. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8957. get: function () {
  8958. return this._isLocked;
  8959. },
  8960. set: function (value) {
  8961. this._isLocked = value;
  8962. },
  8963. enumerable: true,
  8964. configurable: true
  8965. });
  8966. // Methods
  8967. BoundingInfo.prototype.update = function (world) {
  8968. if (this._isLocked) {
  8969. return;
  8970. }
  8971. this.boundingBox._update(world);
  8972. this.boundingSphere._update(world);
  8973. };
  8974. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8975. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8976. return false;
  8977. return this.boundingBox.isInFrustum(frustumPlanes);
  8978. };
  8979. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8980. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8981. };
  8982. BoundingInfo.prototype._checkCollision = function (collider) {
  8983. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8984. };
  8985. BoundingInfo.prototype.intersectsPoint = function (point) {
  8986. if (!this.boundingSphere.centerWorld) {
  8987. return false;
  8988. }
  8989. if (!this.boundingSphere.intersectsPoint(point)) {
  8990. return false;
  8991. }
  8992. if (!this.boundingBox.intersectsPoint(point)) {
  8993. return false;
  8994. }
  8995. return true;
  8996. };
  8997. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8998. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8999. return false;
  9000. }
  9001. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9002. return false;
  9003. }
  9004. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9005. return false;
  9006. }
  9007. if (!precise) {
  9008. return true;
  9009. }
  9010. var box0 = this.boundingBox;
  9011. var box1 = boundingInfo.boundingBox;
  9012. if (!axisOverlap(box0.directions[0], box0, box1))
  9013. return false;
  9014. if (!axisOverlap(box0.directions[1], box0, box1))
  9015. return false;
  9016. if (!axisOverlap(box0.directions[2], box0, box1))
  9017. return false;
  9018. if (!axisOverlap(box1.directions[0], box0, box1))
  9019. return false;
  9020. if (!axisOverlap(box1.directions[1], box0, box1))
  9021. return false;
  9022. if (!axisOverlap(box1.directions[2], box0, box1))
  9023. return false;
  9024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9025. return false;
  9026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9027. return false;
  9028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9029. return false;
  9030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9031. return false;
  9032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9033. return false;
  9034. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9035. return false;
  9036. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9037. return false;
  9038. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9039. return false;
  9040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9041. return false;
  9042. return true;
  9043. };
  9044. return BoundingInfo;
  9045. })();
  9046. BABYLON.BoundingInfo = BoundingInfo;
  9047. })(BABYLON || (BABYLON = {}));
  9048. var BABYLON;
  9049. (function (BABYLON) {
  9050. var Ray = (function () {
  9051. function Ray(origin, direction, length) {
  9052. if (length === void 0) { length = Number.MAX_VALUE; }
  9053. this.origin = origin;
  9054. this.direction = direction;
  9055. this.length = length;
  9056. }
  9057. // Methods
  9058. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9059. var d = 0.0;
  9060. var maxValue = Number.MAX_VALUE;
  9061. var inv;
  9062. var min;
  9063. var max;
  9064. var temp;
  9065. if (Math.abs(this.direction.x) < 0.0000001) {
  9066. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9067. return false;
  9068. }
  9069. }
  9070. else {
  9071. inv = 1.0 / this.direction.x;
  9072. min = (minimum.x - this.origin.x) * inv;
  9073. max = (maximum.x - this.origin.x) * inv;
  9074. if (max === -Infinity) {
  9075. max = Infinity;
  9076. }
  9077. if (min > max) {
  9078. temp = min;
  9079. min = max;
  9080. max = temp;
  9081. }
  9082. d = Math.max(min, d);
  9083. maxValue = Math.min(max, maxValue);
  9084. if (d > maxValue) {
  9085. return false;
  9086. }
  9087. }
  9088. if (Math.abs(this.direction.y) < 0.0000001) {
  9089. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9090. return false;
  9091. }
  9092. }
  9093. else {
  9094. inv = 1.0 / this.direction.y;
  9095. min = (minimum.y - this.origin.y) * inv;
  9096. max = (maximum.y - this.origin.y) * inv;
  9097. if (max === -Infinity) {
  9098. max = Infinity;
  9099. }
  9100. if (min > max) {
  9101. temp = min;
  9102. min = max;
  9103. max = temp;
  9104. }
  9105. d = Math.max(min, d);
  9106. maxValue = Math.min(max, maxValue);
  9107. if (d > maxValue) {
  9108. return false;
  9109. }
  9110. }
  9111. if (Math.abs(this.direction.z) < 0.0000001) {
  9112. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9113. return false;
  9114. }
  9115. }
  9116. else {
  9117. inv = 1.0 / this.direction.z;
  9118. min = (minimum.z - this.origin.z) * inv;
  9119. max = (maximum.z - this.origin.z) * inv;
  9120. if (max === -Infinity) {
  9121. max = Infinity;
  9122. }
  9123. if (min > max) {
  9124. temp = min;
  9125. min = max;
  9126. max = temp;
  9127. }
  9128. d = Math.max(min, d);
  9129. maxValue = Math.min(max, maxValue);
  9130. if (d > maxValue) {
  9131. return false;
  9132. }
  9133. }
  9134. return true;
  9135. };
  9136. Ray.prototype.intersectsBox = function (box) {
  9137. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9138. };
  9139. Ray.prototype.intersectsSphere = function (sphere) {
  9140. var x = sphere.center.x - this.origin.x;
  9141. var y = sphere.center.y - this.origin.y;
  9142. var z = sphere.center.z - this.origin.z;
  9143. var pyth = (x * x) + (y * y) + (z * z);
  9144. var rr = sphere.radius * sphere.radius;
  9145. if (pyth <= rr) {
  9146. return true;
  9147. }
  9148. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9149. if (dot < 0.0) {
  9150. return false;
  9151. }
  9152. var temp = pyth - (dot * dot);
  9153. return temp <= rr;
  9154. };
  9155. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9156. if (!this._edge1) {
  9157. this._edge1 = BABYLON.Vector3.Zero();
  9158. this._edge2 = BABYLON.Vector3.Zero();
  9159. this._pvec = BABYLON.Vector3.Zero();
  9160. this._tvec = BABYLON.Vector3.Zero();
  9161. this._qvec = BABYLON.Vector3.Zero();
  9162. }
  9163. vertex1.subtractToRef(vertex0, this._edge1);
  9164. vertex2.subtractToRef(vertex0, this._edge2);
  9165. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9166. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9167. if (det === 0) {
  9168. return null;
  9169. }
  9170. var invdet = 1 / det;
  9171. this.origin.subtractToRef(vertex0, this._tvec);
  9172. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9173. if (bu < 0 || bu > 1.0) {
  9174. return null;
  9175. }
  9176. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9177. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9178. if (bv < 0 || bu + bv > 1.0) {
  9179. return null;
  9180. }
  9181. //check if the distance is longer than the predefined length.
  9182. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9183. if (distance > this.length) {
  9184. return null;
  9185. }
  9186. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9187. };
  9188. Ray.prototype.intersectsPlane = function (plane) {
  9189. var distance;
  9190. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9191. if (Math.abs(result1) < 9.99999997475243E-07) {
  9192. return null;
  9193. }
  9194. else {
  9195. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9196. distance = (-plane.d - result2) / result1;
  9197. if (distance < 0.0) {
  9198. if (distance < -9.99999997475243E-07) {
  9199. return null;
  9200. }
  9201. else {
  9202. return 0;
  9203. }
  9204. }
  9205. return distance;
  9206. }
  9207. };
  9208. /**
  9209. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9210. * @param sega the first point of the segment to test the intersection against
  9211. * @param segb the second point of the segment to test the intersection against
  9212. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9213. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9214. */
  9215. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9216. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9217. var u = segb.subtract(sega);
  9218. var v = rsegb.subtract(this.origin);
  9219. var w = sega.subtract(this.origin);
  9220. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9221. var b = BABYLON.Vector3.Dot(u, v);
  9222. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9223. var d = BABYLON.Vector3.Dot(u, w);
  9224. var e = BABYLON.Vector3.Dot(v, w);
  9225. var D = a * c - b * b; // always >= 0
  9226. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9227. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9228. // compute the line parameters of the two closest points
  9229. if (D < Ray.smallnum) {
  9230. sN = 0.0; // force using point P0 on segment S1
  9231. sD = 1.0; // to prevent possible division by 0.0 later
  9232. tN = e;
  9233. tD = c;
  9234. }
  9235. else {
  9236. sN = (b * e - c * d);
  9237. tN = (a * e - b * d);
  9238. if (sN < 0.0) {
  9239. sN = 0.0;
  9240. tN = e;
  9241. tD = c;
  9242. }
  9243. else if (sN > sD) {
  9244. sN = sD;
  9245. tN = e + b;
  9246. tD = c;
  9247. }
  9248. }
  9249. if (tN < 0.0) {
  9250. tN = 0.0;
  9251. // recompute sc for this edge
  9252. if (-d < 0.0) {
  9253. sN = 0.0;
  9254. }
  9255. else if (-d > a)
  9256. sN = sD;
  9257. else {
  9258. sN = -d;
  9259. sD = a;
  9260. }
  9261. }
  9262. else if (tN > tD) {
  9263. tN = tD;
  9264. // recompute sc for this edge
  9265. if ((-d + b) < 0.0) {
  9266. sN = 0;
  9267. }
  9268. else if ((-d + b) > a) {
  9269. sN = sD;
  9270. }
  9271. else {
  9272. sN = (-d + b);
  9273. sD = a;
  9274. }
  9275. }
  9276. // finally do the division to get sc and tc
  9277. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9278. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9279. // get the difference of the two closest points
  9280. var qtc = v.multiplyByFloats(tc, tc, tc);
  9281. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9282. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9283. if (isIntersected) {
  9284. return qtc.length();
  9285. }
  9286. return -1;
  9287. };
  9288. // Statics
  9289. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9290. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9291. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9292. var direction = end.subtract(start);
  9293. direction.normalize();
  9294. return new Ray(start, direction);
  9295. };
  9296. /**
  9297. * 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
  9298. * transformed to the given world matrix.
  9299. * @param origin The origin point
  9300. * @param end The end point
  9301. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9302. */
  9303. Ray.CreateNewFromTo = function (origin, end, world) {
  9304. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9305. var direction = end.subtract(origin);
  9306. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9307. direction.normalize();
  9308. return Ray.Transform(new Ray(origin, direction, length), world);
  9309. };
  9310. Ray.Transform = function (ray, matrix) {
  9311. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9312. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9313. newDirection.normalize();
  9314. return new Ray(newOrigin, newDirection, ray.length);
  9315. };
  9316. Ray.smallnum = 0.00000001;
  9317. Ray.rayl = 10e8;
  9318. return Ray;
  9319. })();
  9320. BABYLON.Ray = Ray;
  9321. })(BABYLON || (BABYLON = {}));
  9322. var BABYLON;
  9323. (function (BABYLON) {
  9324. var AbstractMesh = (function (_super) {
  9325. __extends(AbstractMesh, _super);
  9326. // Constructor
  9327. function AbstractMesh(name, scene) {
  9328. var _this = this;
  9329. _super.call(this, name, scene);
  9330. // Events
  9331. /**
  9332. * An event triggered when the mesh is disposed.
  9333. * @type {BABYLON.Observable}
  9334. */
  9335. this.onDisposeObservable = new BABYLON.Observable();
  9336. /**
  9337. * An event triggered when this mesh collides with another one
  9338. * @type {BABYLON.Observable}
  9339. */
  9340. this.onCollideObservable = new BABYLON.Observable();
  9341. /**
  9342. * An event triggered when the collision's position changes
  9343. * @type {BABYLON.Observable}
  9344. */
  9345. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9346. /**
  9347. * An event triggered after the world matrix is updated
  9348. * @type {BABYLON.Observable}
  9349. */
  9350. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9351. // Properties
  9352. this.definedFacingForward = true; // orientation for POV movement & rotation
  9353. this.position = new BABYLON.Vector3(0, 0, 0);
  9354. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9355. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9356. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9357. this.visibility = 1.0;
  9358. this.alphaIndex = Number.MAX_VALUE;
  9359. this.infiniteDistance = false;
  9360. this.isVisible = true;
  9361. this.isPickable = true;
  9362. this.showBoundingBox = false;
  9363. this.showSubMeshesBoundingBox = false;
  9364. this.isBlocker = false;
  9365. this.renderingGroupId = 0;
  9366. this.receiveShadows = false;
  9367. this.renderOutline = false;
  9368. this.outlineColor = BABYLON.Color3.Red();
  9369. this.outlineWidth = 0.02;
  9370. this.renderOverlay = false;
  9371. this.overlayColor = BABYLON.Color3.Red();
  9372. this.overlayAlpha = 0.5;
  9373. this.hasVertexAlpha = false;
  9374. this.useVertexColors = true;
  9375. this.applyFog = true;
  9376. this.computeBonesUsingShaders = true;
  9377. this.scalingDeterminant = 1;
  9378. this.numBoneInfluencers = 4;
  9379. this.useOctreeForRenderingSelection = true;
  9380. this.useOctreeForPicking = true;
  9381. this.useOctreeForCollisions = true;
  9382. this.layerMask = 0x0FFFFFFF;
  9383. this.alwaysSelectAsActiveMesh = false;
  9384. // Collisions
  9385. this._checkCollisions = false;
  9386. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9387. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9388. this._collider = new BABYLON.Collider();
  9389. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9390. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9391. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9392. // Edges
  9393. this.edgesWidth = 1;
  9394. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9395. // Cache
  9396. this._localWorld = BABYLON.Matrix.Zero();
  9397. this._worldMatrix = BABYLON.Matrix.Zero();
  9398. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9399. this._absolutePosition = BABYLON.Vector3.Zero();
  9400. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9401. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9402. this._isDirty = false;
  9403. this._pivotMatrix = BABYLON.Matrix.Identity();
  9404. this._isDisposed = false;
  9405. this._renderId = 0;
  9406. this._intersectionsInProgress = new Array();
  9407. this._isWorldMatrixFrozen = false;
  9408. this._unIndexed = false;
  9409. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9410. if (collidedMesh === void 0) { collidedMesh = null; }
  9411. //TODO move this to the collision coordinator!
  9412. if (_this.getScene().workerCollisions)
  9413. newPosition.multiplyInPlace(_this._collider.radius);
  9414. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9415. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9416. _this.position.addInPlace(_this._diffPositionForCollisions);
  9417. }
  9418. if (collidedMesh) {
  9419. _this.onCollideObservable.notifyObservers(collidedMesh);
  9420. }
  9421. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9422. };
  9423. scene.addMesh(this);
  9424. }
  9425. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9426. get: function () {
  9427. return AbstractMesh._BILLBOARDMODE_NONE;
  9428. },
  9429. enumerable: true,
  9430. configurable: true
  9431. });
  9432. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9433. get: function () {
  9434. return AbstractMesh._BILLBOARDMODE_X;
  9435. },
  9436. enumerable: true,
  9437. configurable: true
  9438. });
  9439. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9440. get: function () {
  9441. return AbstractMesh._BILLBOARDMODE_Y;
  9442. },
  9443. enumerable: true,
  9444. configurable: true
  9445. });
  9446. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9447. get: function () {
  9448. return AbstractMesh._BILLBOARDMODE_Z;
  9449. },
  9450. enumerable: true,
  9451. configurable: true
  9452. });
  9453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9454. get: function () {
  9455. return AbstractMesh._BILLBOARDMODE_ALL;
  9456. },
  9457. enumerable: true,
  9458. configurable: true
  9459. });
  9460. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9461. set: function (callback) {
  9462. if (this._onDisposeObserver) {
  9463. this.onDisposeObservable.remove(this._onDisposeObserver);
  9464. }
  9465. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9466. },
  9467. enumerable: true,
  9468. configurable: true
  9469. });
  9470. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9471. set: function (callback) {
  9472. if (this._onCollideObserver) {
  9473. this.onCollideObservable.remove(this._onCollideObserver);
  9474. }
  9475. this._onCollideObserver = this.onCollideObservable.add(callback);
  9476. },
  9477. enumerable: true,
  9478. configurable: true
  9479. });
  9480. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9481. set: function (callback) {
  9482. if (this._onCollisionPositionChangeObserver) {
  9483. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9484. }
  9485. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9491. get: function () {
  9492. return this._skeleton;
  9493. },
  9494. set: function (value) {
  9495. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9496. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9497. }
  9498. if (value && value.needInitialSkinMatrix) {
  9499. value._registerMeshWithPoseMatrix(this);
  9500. }
  9501. this._skeleton = value;
  9502. if (!this._skeleton) {
  9503. this._bonesTransformMatrices = null;
  9504. }
  9505. },
  9506. enumerable: true,
  9507. configurable: true
  9508. });
  9509. /**
  9510. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9511. */
  9512. AbstractMesh.prototype.toString = function (fullDetails) {
  9513. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9514. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9515. if (this._skeleton) {
  9516. ret += ", skeleton: " + this._skeleton.name;
  9517. }
  9518. if (fullDetails) {
  9519. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9520. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9521. }
  9522. return ret;
  9523. };
  9524. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9525. /**
  9526. * Getting the rotation object.
  9527. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9528. */
  9529. get: function () {
  9530. return this._rotation;
  9531. },
  9532. set: function (newRotation) {
  9533. this._rotation = newRotation;
  9534. },
  9535. enumerable: true,
  9536. configurable: true
  9537. });
  9538. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9539. get: function () {
  9540. return this._scaling;
  9541. },
  9542. set: function (newScaling) {
  9543. this._scaling = newScaling;
  9544. if (this.physicsImpostor) {
  9545. this.physicsImpostor.forceUpdate();
  9546. }
  9547. },
  9548. enumerable: true,
  9549. configurable: true
  9550. });
  9551. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9552. get: function () {
  9553. return this._rotationQuaternion;
  9554. },
  9555. set: function (quaternion) {
  9556. this._rotationQuaternion = quaternion;
  9557. //reset the rotation vector.
  9558. if (quaternion && this.rotation.length()) {
  9559. this.rotation.copyFromFloats(0, 0, 0);
  9560. }
  9561. },
  9562. enumerable: true,
  9563. configurable: true
  9564. });
  9565. // Methods
  9566. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9567. this._poseMatrix.copyFrom(matrix);
  9568. };
  9569. AbstractMesh.prototype.getPoseMatrix = function () {
  9570. return this._poseMatrix;
  9571. };
  9572. AbstractMesh.prototype.disableEdgesRendering = function () {
  9573. if (this._edgesRenderer !== undefined) {
  9574. this._edgesRenderer.dispose();
  9575. this._edgesRenderer = undefined;
  9576. }
  9577. };
  9578. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9579. if (epsilon === void 0) { epsilon = 0.95; }
  9580. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9581. this.disableEdgesRendering();
  9582. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9583. };
  9584. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9585. get: function () {
  9586. return false;
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. AbstractMesh.prototype.getLOD = function (camera) {
  9592. return this;
  9593. };
  9594. AbstractMesh.prototype.getTotalVertices = function () {
  9595. return 0;
  9596. };
  9597. AbstractMesh.prototype.getIndices = function () {
  9598. return null;
  9599. };
  9600. AbstractMesh.prototype.getVerticesData = function (kind) {
  9601. return null;
  9602. };
  9603. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9604. return false;
  9605. };
  9606. AbstractMesh.prototype.getBoundingInfo = function () {
  9607. if (this._masterMesh) {
  9608. return this._masterMesh.getBoundingInfo();
  9609. }
  9610. if (!this._boundingInfo) {
  9611. this._updateBoundingInfo();
  9612. }
  9613. return this._boundingInfo;
  9614. };
  9615. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  9616. this._boundingInfo = boundingInfo;
  9617. };
  9618. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9619. get: function () {
  9620. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. AbstractMesh.prototype._preActivate = function () {
  9626. };
  9627. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  9628. };
  9629. AbstractMesh.prototype._activate = function (renderId) {
  9630. this._renderId = renderId;
  9631. };
  9632. AbstractMesh.prototype.getWorldMatrix = function () {
  9633. if (this._masterMesh) {
  9634. return this._masterMesh.getWorldMatrix();
  9635. }
  9636. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9637. this.computeWorldMatrix();
  9638. }
  9639. return this._worldMatrix;
  9640. };
  9641. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9642. get: function () {
  9643. return this._worldMatrix;
  9644. },
  9645. enumerable: true,
  9646. configurable: true
  9647. });
  9648. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9649. get: function () {
  9650. return this._absolutePosition;
  9651. },
  9652. enumerable: true,
  9653. configurable: true
  9654. });
  9655. AbstractMesh.prototype.freezeWorldMatrix = function () {
  9656. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  9657. this.computeWorldMatrix(true);
  9658. this._isWorldMatrixFrozen = true;
  9659. };
  9660. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  9661. this._isWorldMatrixFrozen = false;
  9662. this.computeWorldMatrix(true);
  9663. };
  9664. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  9665. get: function () {
  9666. return this._isWorldMatrixFrozen;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9672. axis.normalize();
  9673. if (!this.rotationQuaternion) {
  9674. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9675. this.rotation = BABYLON.Vector3.Zero();
  9676. }
  9677. var rotationQuaternion;
  9678. if (!space || space === BABYLON.Space.LOCAL) {
  9679. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9680. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  9681. }
  9682. else {
  9683. if (this.parent) {
  9684. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9685. invertParentWorldMatrix.invert();
  9686. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9687. }
  9688. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  9689. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  9690. }
  9691. };
  9692. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9693. var displacementVector = axis.scale(distance);
  9694. if (!space || space === BABYLON.Space.LOCAL) {
  9695. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9696. this.setPositionWithLocalVector(tempV3);
  9697. }
  9698. else {
  9699. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9700. }
  9701. };
  9702. AbstractMesh.prototype.getAbsolutePosition = function () {
  9703. this.computeWorldMatrix();
  9704. return this._absolutePosition;
  9705. };
  9706. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9707. if (!absolutePosition) {
  9708. return;
  9709. }
  9710. var absolutePositionX;
  9711. var absolutePositionY;
  9712. var absolutePositionZ;
  9713. if (absolutePosition.x === undefined) {
  9714. if (arguments.length < 3) {
  9715. return;
  9716. }
  9717. absolutePositionX = arguments[0];
  9718. absolutePositionY = arguments[1];
  9719. absolutePositionZ = arguments[2];
  9720. }
  9721. else {
  9722. absolutePositionX = absolutePosition.x;
  9723. absolutePositionY = absolutePosition.y;
  9724. absolutePositionZ = absolutePosition.z;
  9725. }
  9726. if (this.parent) {
  9727. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9728. invertParentWorldMatrix.invert();
  9729. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9730. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9731. }
  9732. else {
  9733. this.position.x = absolutePositionX;
  9734. this.position.y = absolutePositionY;
  9735. this.position.z = absolutePositionZ;
  9736. }
  9737. };
  9738. // ================================== Point of View Movement =================================
  9739. /**
  9740. * Perform relative position change from the point of view of behind the front of the mesh.
  9741. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9742. * Supports definition of mesh facing forward or backward.
  9743. * @param {number} amountRight
  9744. * @param {number} amountUp
  9745. * @param {number} amountForward
  9746. */
  9747. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9748. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9749. };
  9750. /**
  9751. * Calculate relative position change from the point of view of behind the front of the mesh.
  9752. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9753. * Supports definition of mesh facing forward or backward.
  9754. * @param {number} amountRight
  9755. * @param {number} amountUp
  9756. * @param {number} amountForward
  9757. */
  9758. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9759. var rotMatrix = new BABYLON.Matrix();
  9760. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9761. rotQuaternion.toRotationMatrix(rotMatrix);
  9762. var translationDelta = BABYLON.Vector3.Zero();
  9763. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9764. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9765. return translationDelta;
  9766. };
  9767. // ================================== Point of View Rotation =================================
  9768. /**
  9769. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9770. * Supports definition of mesh facing forward or backward.
  9771. * @param {number} flipBack
  9772. * @param {number} twirlClockwise
  9773. * @param {number} tiltRight
  9774. */
  9775. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9776. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9777. };
  9778. /**
  9779. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9780. * Supports definition of mesh facing forward or backward.
  9781. * @param {number} flipBack
  9782. * @param {number} twirlClockwise
  9783. * @param {number} tiltRight
  9784. */
  9785. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9786. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9787. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9788. };
  9789. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9790. this._pivotMatrix = matrix;
  9791. this._cache.pivotMatrixUpdated = true;
  9792. };
  9793. AbstractMesh.prototype.getPivotMatrix = function () {
  9794. return this._pivotMatrix;
  9795. };
  9796. AbstractMesh.prototype._isSynchronized = function () {
  9797. if (this._isDirty) {
  9798. return false;
  9799. }
  9800. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9801. return false;
  9802. if (this._cache.pivotMatrixUpdated) {
  9803. return false;
  9804. }
  9805. if (this.infiniteDistance) {
  9806. return false;
  9807. }
  9808. if (!this._cache.position.equals(this.position))
  9809. return false;
  9810. if (this.rotationQuaternion) {
  9811. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9812. return false;
  9813. }
  9814. else {
  9815. if (!this._cache.rotation.equals(this.rotation))
  9816. return false;
  9817. }
  9818. if (!this._cache.scaling.equals(this.scaling))
  9819. return false;
  9820. return true;
  9821. };
  9822. AbstractMesh.prototype._initCache = function () {
  9823. _super.prototype._initCache.call(this);
  9824. this._cache.localMatrixUpdated = false;
  9825. this._cache.position = BABYLON.Vector3.Zero();
  9826. this._cache.scaling = BABYLON.Vector3.Zero();
  9827. this._cache.rotation = BABYLON.Vector3.Zero();
  9828. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9829. this._cache.billboardMode = -1;
  9830. };
  9831. AbstractMesh.prototype.markAsDirty = function (property) {
  9832. if (property === "rotation") {
  9833. this.rotationQuaternion = null;
  9834. }
  9835. this._currentRenderId = Number.MAX_VALUE;
  9836. this._isDirty = true;
  9837. };
  9838. AbstractMesh.prototype._updateBoundingInfo = function () {
  9839. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9840. this._boundingInfo.update(this.worldMatrixFromCache);
  9841. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9842. };
  9843. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9844. if (!this.subMeshes) {
  9845. return;
  9846. }
  9847. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9848. var subMesh = this.subMeshes[subIndex];
  9849. if (!subMesh.IsGlobal) {
  9850. subMesh.updateBoundingInfo(matrix);
  9851. }
  9852. }
  9853. };
  9854. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9855. if (this._isWorldMatrixFrozen) {
  9856. return this._worldMatrix;
  9857. }
  9858. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  9859. this._currentRenderId = this.getScene().getRenderId();
  9860. return this._worldMatrix;
  9861. }
  9862. this._cache.position.copyFrom(this.position);
  9863. this._cache.scaling.copyFrom(this.scaling);
  9864. this._cache.pivotMatrixUpdated = false;
  9865. this._cache.billboardMode = this.billboardMode;
  9866. this._currentRenderId = this.getScene().getRenderId();
  9867. this._isDirty = false;
  9868. // Scaling
  9869. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  9870. // Rotation
  9871. //rotate, if quaternion is set and rotation was used
  9872. if (this.rotationQuaternion) {
  9873. var len = this.rotation.length();
  9874. if (len) {
  9875. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  9876. this.rotation.copyFromFloats(0, 0, 0);
  9877. }
  9878. }
  9879. if (this.rotationQuaternion) {
  9880. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  9881. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9882. }
  9883. else {
  9884. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  9885. this._cache.rotation.copyFrom(this.rotation);
  9886. }
  9887. // Translation
  9888. if (this.infiniteDistance && !this.parent) {
  9889. var camera = this.getScene().activeCamera;
  9890. if (camera) {
  9891. var cameraWorldMatrix = camera.getWorldMatrix();
  9892. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9893. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  9894. }
  9895. }
  9896. else {
  9897. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  9898. }
  9899. // Composing transformations
  9900. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  9901. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  9902. // Billboarding
  9903. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9904. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  9905. var localPosition = BABYLON.Tmp.Vector3[0];
  9906. if (this.parent && this.parent.getWorldMatrix) {
  9907. this._markSyncedWithParent();
  9908. var parentMatrix;
  9909. if (this._meshToBoneReferal) {
  9910. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9911. parentMatrix = BABYLON.Tmp.Matrix[6];
  9912. }
  9913. else {
  9914. parentMatrix = this.parent.getWorldMatrix();
  9915. }
  9916. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9917. localPosition = BABYLON.Tmp.Vector3[1];
  9918. }
  9919. var zero = this.getScene().activeCamera.globalPosition.clone();
  9920. if (this.parent && this.parent.position) {
  9921. localPosition.addInPlace(this.parent.position);
  9922. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9923. }
  9924. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9925. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9926. zero.x = localPosition.x + BABYLON.Epsilon;
  9927. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9928. zero.y = localPosition.y + BABYLON.Epsilon;
  9929. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9930. zero.z = localPosition.z + BABYLON.Epsilon;
  9931. }
  9932. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9933. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9934. BABYLON.Tmp.Matrix[3].invert();
  9935. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9936. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9937. }
  9938. // Local world
  9939. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9940. // Parent
  9941. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9942. this._markSyncedWithParent();
  9943. if (this._meshToBoneReferal) {
  9944. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9945. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9946. }
  9947. else {
  9948. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9949. }
  9950. }
  9951. else {
  9952. this._worldMatrix.copyFrom(this._localWorld);
  9953. }
  9954. // Bounding info
  9955. this._updateBoundingInfo();
  9956. // Absolute position
  9957. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9958. // Callbacks
  9959. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9960. if (!this._poseMatrix) {
  9961. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9962. }
  9963. return this._worldMatrix;
  9964. };
  9965. /**
  9966. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9967. * @param func: callback function to add
  9968. */
  9969. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9970. this.onAfterWorldMatrixUpdateObservable.add(func);
  9971. };
  9972. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9973. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9974. };
  9975. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9976. this.computeWorldMatrix();
  9977. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9978. };
  9979. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9980. this.computeWorldMatrix();
  9981. var invLocalWorldMatrix = this._localWorld.clone();
  9982. invLocalWorldMatrix.invert();
  9983. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9984. };
  9985. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9986. this.computeWorldMatrix(true);
  9987. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9988. };
  9989. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  9990. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9991. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9992. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9993. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9994. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9995. /// <returns>Mesh oriented towards targetMesh</returns>
  9996. if (yawCor === void 0) { yawCor = 0; }
  9997. if (pitchCor === void 0) { pitchCor = 0; }
  9998. if (rollCor === void 0) { rollCor = 0; }
  9999. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10000. var dv = AbstractMesh._lookAtVectorCache;
  10001. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10002. targetPoint.subtractToRef(pos, dv);
  10003. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10004. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10005. var pitch = Math.atan2(dv.y, len);
  10006. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10007. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10008. };
  10009. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10010. this._meshToBoneReferal = affectedMesh;
  10011. this.parent = bone;
  10012. if (bone.getWorldMatrix().determinant() < 0) {
  10013. this.scalingDeterminant *= -1;
  10014. }
  10015. };
  10016. AbstractMesh.prototype.detachFromBone = function () {
  10017. if (this.parent.getWorldMatrix().determinant() < 0) {
  10018. this.scalingDeterminant *= -1;
  10019. }
  10020. this._meshToBoneReferal = null;
  10021. this.parent = null;
  10022. };
  10023. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10024. return this._boundingInfo.isInFrustum(frustumPlanes);
  10025. };
  10026. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10027. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10028. ;
  10029. };
  10030. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10031. if (!this._boundingInfo || !mesh._boundingInfo) {
  10032. return false;
  10033. }
  10034. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10035. };
  10036. AbstractMesh.prototype.intersectsPoint = function (point) {
  10037. if (!this._boundingInfo) {
  10038. return false;
  10039. }
  10040. return this._boundingInfo.intersectsPoint(point);
  10041. };
  10042. // Physics
  10043. /**
  10044. * @Deprecated. Use new PhysicsImpostor instead.
  10045. * */
  10046. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10047. //legacy support
  10048. if (impostor.impostor) {
  10049. options = impostor;
  10050. impostor = impostor.impostor;
  10051. }
  10052. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10053. return this.physicsImpostor.physicsBody;
  10054. };
  10055. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10056. return this.physicsImpostor;
  10057. };
  10058. /**
  10059. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10060. */
  10061. AbstractMesh.prototype.getPhysicsMass = function () {
  10062. return this.physicsImpostor.getParam("mass");
  10063. };
  10064. /**
  10065. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10066. */
  10067. AbstractMesh.prototype.getPhysicsFriction = function () {
  10068. return this.physicsImpostor.getParam("friction");
  10069. };
  10070. /**
  10071. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10072. */
  10073. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10074. return this.physicsImpostor.getParam("restitution");
  10075. };
  10076. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10077. if (!camera) {
  10078. camera = this.getScene().activeCamera;
  10079. }
  10080. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10081. };
  10082. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10083. if (!camera) {
  10084. camera = this.getScene().activeCamera;
  10085. }
  10086. return this.absolutePosition.subtract(camera.position).length();
  10087. };
  10088. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10089. if (!this.physicsImpostor) {
  10090. return;
  10091. }
  10092. this.physicsImpostor.applyImpulse(force, contactPoint);
  10093. };
  10094. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10095. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10096. return;
  10097. }
  10098. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10099. mainPivot: pivot1,
  10100. connectedPivot: pivot2,
  10101. nativeParams: options
  10102. });
  10103. };
  10104. /**
  10105. * @Deprecated
  10106. */
  10107. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10108. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10109. this.updatePhysicsBody();
  10110. };
  10111. /**
  10112. * @Deprecated
  10113. * Calling this function is not needed anymore.
  10114. * The physics engine takes care of transofmration automatically.
  10115. */
  10116. AbstractMesh.prototype.updatePhysicsBody = function () {
  10117. //Unneeded
  10118. };
  10119. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10120. // Collisions
  10121. get: function () {
  10122. return this._checkCollisions;
  10123. },
  10124. set: function (collisionEnabled) {
  10125. this._checkCollisions = collisionEnabled;
  10126. if (this.getScene().workerCollisions) {
  10127. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10128. }
  10129. },
  10130. enumerable: true,
  10131. configurable: true
  10132. });
  10133. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10134. var globalPosition = this.getAbsolutePosition();
  10135. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10136. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10137. this._collider.radius = this.ellipsoid;
  10138. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10139. };
  10140. // Submeshes octree
  10141. /**
  10142. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10143. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10144. */
  10145. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10146. if (maxCapacity === void 0) { maxCapacity = 64; }
  10147. if (maxDepth === void 0) { maxDepth = 2; }
  10148. if (!this._submeshesOctree) {
  10149. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10150. }
  10151. this.computeWorldMatrix(true);
  10152. // Update octree
  10153. var bbox = this.getBoundingInfo().boundingBox;
  10154. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10155. return this._submeshesOctree;
  10156. };
  10157. // Collisions
  10158. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10159. this._generatePointsArray();
  10160. // Transformation
  10161. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10162. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10163. subMesh._lastColliderWorldVertices = [];
  10164. subMesh._trianglePlanes = [];
  10165. var start = subMesh.verticesStart;
  10166. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10167. for (var i = start; i < end; i++) {
  10168. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10169. }
  10170. }
  10171. // Collide
  10172. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10173. if (collider.collisionFound) {
  10174. collider.collidedMesh = this;
  10175. }
  10176. };
  10177. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10178. var subMeshes;
  10179. var len;
  10180. // Octrees
  10181. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10182. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10183. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10184. len = intersections.length;
  10185. subMeshes = intersections.data;
  10186. }
  10187. else {
  10188. subMeshes = this.subMeshes;
  10189. len = subMeshes.length;
  10190. }
  10191. for (var index = 0; index < len; index++) {
  10192. var subMesh = subMeshes[index];
  10193. // Bounding test
  10194. if (len > 1 && !subMesh._checkCollision(collider))
  10195. continue;
  10196. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10197. }
  10198. };
  10199. AbstractMesh.prototype._checkCollision = function (collider) {
  10200. // Bounding box test
  10201. if (!this._boundingInfo._checkCollision(collider))
  10202. return;
  10203. // Transformation matrix
  10204. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10205. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10206. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10207. };
  10208. // Picking
  10209. AbstractMesh.prototype._generatePointsArray = function () {
  10210. return false;
  10211. };
  10212. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10213. var pickingInfo = new BABYLON.PickingInfo();
  10214. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10215. return pickingInfo;
  10216. }
  10217. if (!this._generatePointsArray()) {
  10218. return pickingInfo;
  10219. }
  10220. var intersectInfo = null;
  10221. // Octrees
  10222. var subMeshes;
  10223. var len;
  10224. if (this._submeshesOctree && this.useOctreeForPicking) {
  10225. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10226. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10227. len = intersections.length;
  10228. subMeshes = intersections.data;
  10229. }
  10230. else {
  10231. subMeshes = this.subMeshes;
  10232. len = subMeshes.length;
  10233. }
  10234. for (var index = 0; index < len; index++) {
  10235. var subMesh = subMeshes[index];
  10236. // Bounding test
  10237. if (len > 1 && !subMesh.canIntersects(ray))
  10238. continue;
  10239. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10240. if (currentIntersectInfo) {
  10241. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10242. intersectInfo = currentIntersectInfo;
  10243. intersectInfo.subMeshId = index;
  10244. if (fastCheck) {
  10245. break;
  10246. }
  10247. }
  10248. }
  10249. }
  10250. if (intersectInfo) {
  10251. // Get picked point
  10252. var world = this.getWorldMatrix();
  10253. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10254. var direction = ray.direction.clone();
  10255. direction = direction.scale(intersectInfo.distance);
  10256. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10257. var pickedPoint = worldOrigin.add(worldDirection);
  10258. // Return result
  10259. pickingInfo.hit = true;
  10260. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10261. pickingInfo.pickedPoint = pickedPoint;
  10262. pickingInfo.pickedMesh = this;
  10263. pickingInfo.bu = intersectInfo.bu;
  10264. pickingInfo.bv = intersectInfo.bv;
  10265. pickingInfo.faceId = intersectInfo.faceId;
  10266. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10267. return pickingInfo;
  10268. }
  10269. return pickingInfo;
  10270. };
  10271. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10272. return null;
  10273. };
  10274. AbstractMesh.prototype.releaseSubMeshes = function () {
  10275. if (this.subMeshes) {
  10276. while (this.subMeshes.length) {
  10277. this.subMeshes[0].dispose();
  10278. }
  10279. }
  10280. else {
  10281. this.subMeshes = new Array();
  10282. }
  10283. };
  10284. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10285. var _this = this;
  10286. var index;
  10287. // Action manager
  10288. if (this.actionManager) {
  10289. this.actionManager.dispose();
  10290. this.actionManager = null;
  10291. }
  10292. // Skeleton
  10293. this.skeleton = null;
  10294. // Animations
  10295. this.getScene().stopAnimation(this);
  10296. // Physics
  10297. if (this.physicsImpostor) {
  10298. this.physicsImpostor.dispose();
  10299. }
  10300. // Intersections in progress
  10301. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10302. var other = this._intersectionsInProgress[index];
  10303. var pos = other._intersectionsInProgress.indexOf(this);
  10304. other._intersectionsInProgress.splice(pos, 1);
  10305. }
  10306. this._intersectionsInProgress = [];
  10307. // Lights
  10308. var lights = this.getScene().lights;
  10309. lights.forEach(function (light) {
  10310. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10311. if (meshIndex !== -1) {
  10312. light.includedOnlyMeshes.splice(meshIndex, 1);
  10313. }
  10314. meshIndex = light.excludedMeshes.indexOf(_this);
  10315. if (meshIndex !== -1) {
  10316. light.excludedMeshes.splice(meshIndex, 1);
  10317. }
  10318. });
  10319. // Edges
  10320. if (this._edgesRenderer) {
  10321. this._edgesRenderer.dispose();
  10322. this._edgesRenderer = null;
  10323. }
  10324. // SubMeshes
  10325. this.releaseSubMeshes();
  10326. // Remove from scene
  10327. this.getScene().removeMesh(this);
  10328. if (!doNotRecurse) {
  10329. // Particles
  10330. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10331. if (this.getScene().particleSystems[index].emitter === this) {
  10332. this.getScene().particleSystems[index].dispose();
  10333. index--;
  10334. }
  10335. }
  10336. // Children
  10337. var objects = this.getDescendants(true);
  10338. for (index = 0; index < objects.length; index++) {
  10339. objects[index].dispose();
  10340. }
  10341. }
  10342. else {
  10343. var childMeshes = this.getChildMeshes(true);
  10344. for (index = 0; index < childMeshes.length; index++) {
  10345. var child = childMeshes[index];
  10346. child.parent = null;
  10347. child.computeWorldMatrix(true);
  10348. }
  10349. }
  10350. _super.prototype.dispose.call(this);
  10351. this.onAfterWorldMatrixUpdateObservable.clear();
  10352. this.onCollideObservable.clear();
  10353. this.onCollisionPositionChangeObservable.clear();
  10354. this._isDisposed = true;
  10355. // Callback
  10356. this.onDisposeObservable.notifyObservers(this);
  10357. this.onDisposeObservable.clear();
  10358. };
  10359. // Statics
  10360. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10361. AbstractMesh._BILLBOARDMODE_X = 1;
  10362. AbstractMesh._BILLBOARDMODE_Y = 2;
  10363. AbstractMesh._BILLBOARDMODE_Z = 4;
  10364. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10365. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10366. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10367. return AbstractMesh;
  10368. })(BABYLON.Node);
  10369. BABYLON.AbstractMesh = AbstractMesh;
  10370. })(BABYLON || (BABYLON = {}));
  10371. var BABYLON;
  10372. (function (BABYLON) {
  10373. var Light = (function (_super) {
  10374. __extends(Light, _super);
  10375. function Light(name, scene) {
  10376. _super.call(this, name, scene);
  10377. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10378. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10379. this.intensity = 1.0;
  10380. this.range = Number.MAX_VALUE;
  10381. this.includeOnlyWithLayerMask = 0;
  10382. this.includedOnlyMeshes = new Array();
  10383. this.excludedMeshes = new Array();
  10384. this.excludeWithLayerMask = 0;
  10385. // PBR Properties.
  10386. this.radius = 0.00001;
  10387. this._excludedMeshesIds = new Array();
  10388. this._includedOnlyMeshesIds = new Array();
  10389. scene.addLight(this);
  10390. }
  10391. /**
  10392. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10393. */
  10394. Light.prototype.toString = function (fullDetails) {
  10395. var ret = "Name: " + this.name;
  10396. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10397. if (this.animations) {
  10398. for (var i = 0; i < this.animations.length; i++) {
  10399. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10400. }
  10401. }
  10402. if (fullDetails) {
  10403. }
  10404. return ret;
  10405. };
  10406. Light.prototype.getShadowGenerator = function () {
  10407. return this._shadowGenerator;
  10408. };
  10409. Light.prototype.getAbsolutePosition = function () {
  10410. return BABYLON.Vector3.Zero();
  10411. };
  10412. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10413. };
  10414. Light.prototype._getWorldMatrix = function () {
  10415. return BABYLON.Matrix.Identity();
  10416. };
  10417. Light.prototype.canAffectMesh = function (mesh) {
  10418. if (!mesh) {
  10419. return true;
  10420. }
  10421. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10422. return false;
  10423. }
  10424. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10425. return false;
  10426. }
  10427. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10428. return false;
  10429. }
  10430. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10431. return false;
  10432. }
  10433. return true;
  10434. };
  10435. Light.prototype.getWorldMatrix = function () {
  10436. this._currentRenderId = this.getScene().getRenderId();
  10437. var worldMatrix = this._getWorldMatrix();
  10438. if (this.parent && this.parent.getWorldMatrix) {
  10439. if (!this._parentedWorldMatrix) {
  10440. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10441. }
  10442. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10443. this._markSyncedWithParent();
  10444. return this._parentedWorldMatrix;
  10445. }
  10446. return worldMatrix;
  10447. };
  10448. Light.prototype.dispose = function () {
  10449. if (this._shadowGenerator) {
  10450. this._shadowGenerator.dispose();
  10451. this._shadowGenerator = null;
  10452. }
  10453. // Animations
  10454. this.getScene().stopAnimation(this);
  10455. // Remove from scene
  10456. this.getScene().removeLight(this);
  10457. _super.prototype.dispose.call(this);
  10458. };
  10459. Light.prototype.getTypeID = function () {
  10460. return 0;
  10461. };
  10462. Light.prototype.clone = function (name) {
  10463. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10464. };
  10465. Light.prototype.serialize = function () {
  10466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10467. // Type
  10468. serializationObject.type = this.getTypeID();
  10469. // Parent
  10470. if (this.parent) {
  10471. serializationObject.parentId = this.parent.id;
  10472. }
  10473. // Inclusion / exclusions
  10474. if (this.excludedMeshes.length > 0) {
  10475. serializationObject.excludedMeshesIds = [];
  10476. this.excludedMeshes.forEach(function (mesh) {
  10477. serializationObject.excludedMeshesIds.push(mesh.id);
  10478. });
  10479. }
  10480. if (this.includedOnlyMeshes.length > 0) {
  10481. serializationObject.includedOnlyMeshesIds = [];
  10482. this.includedOnlyMeshes.forEach(function (mesh) {
  10483. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10484. });
  10485. }
  10486. // Animations
  10487. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10488. serializationObject.ranges = this.serializeAnimationRanges();
  10489. return serializationObject;
  10490. };
  10491. Light.GetConstructorFromName = function (type, name, scene) {
  10492. switch (type) {
  10493. case 0:
  10494. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10495. case 1:
  10496. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10497. case 2:
  10498. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10499. case 3:
  10500. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10501. }
  10502. };
  10503. Light.Parse = function (parsedLight, scene) {
  10504. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10505. // Inclusion / exclusions
  10506. if (parsedLight.excludedMeshesIds) {
  10507. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10508. }
  10509. if (parsedLight.includedOnlyMeshesIds) {
  10510. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10511. }
  10512. // Parent
  10513. if (parsedLight.parentId) {
  10514. light._waitingParentId = parsedLight.parentId;
  10515. }
  10516. // Animations
  10517. if (parsedLight.animations) {
  10518. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10519. var parsedAnimation = parsedLight.animations[animationIndex];
  10520. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10521. }
  10522. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10523. }
  10524. if (parsedLight.autoAnimate) {
  10525. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10526. }
  10527. return light;
  10528. };
  10529. __decorate([
  10530. BABYLON.serializeAsColor3()
  10531. ], Light.prototype, "diffuse", void 0);
  10532. __decorate([
  10533. BABYLON.serializeAsColor3()
  10534. ], Light.prototype, "specular", void 0);
  10535. __decorate([
  10536. BABYLON.serialize()
  10537. ], Light.prototype, "intensity", void 0);
  10538. __decorate([
  10539. BABYLON.serialize()
  10540. ], Light.prototype, "range", void 0);
  10541. __decorate([
  10542. BABYLON.serialize()
  10543. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10544. __decorate([
  10545. BABYLON.serialize()
  10546. ], Light.prototype, "excludeWithLayerMask", void 0);
  10547. __decorate([
  10548. BABYLON.serialize()
  10549. ], Light.prototype, "radius", void 0);
  10550. return Light;
  10551. })(BABYLON.Node);
  10552. BABYLON.Light = Light;
  10553. })(BABYLON || (BABYLON = {}));
  10554. var BABYLON;
  10555. (function (BABYLON) {
  10556. var PointLight = (function (_super) {
  10557. __extends(PointLight, _super);
  10558. function PointLight(name, position, scene) {
  10559. _super.call(this, name, scene);
  10560. this.position = position;
  10561. }
  10562. PointLight.prototype.getAbsolutePosition = function () {
  10563. return this.transformedPosition ? this.transformedPosition : this.position;
  10564. };
  10565. PointLight.prototype.computeTransformedPosition = function () {
  10566. if (this.parent && this.parent.getWorldMatrix) {
  10567. if (!this.transformedPosition) {
  10568. this.transformedPosition = BABYLON.Vector3.Zero();
  10569. }
  10570. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10571. return true;
  10572. }
  10573. return false;
  10574. };
  10575. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10576. if (this.parent && this.parent.getWorldMatrix) {
  10577. this.computeTransformedPosition();
  10578. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10579. return;
  10580. }
  10581. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10582. };
  10583. PointLight.prototype.needCube = function () {
  10584. return true;
  10585. };
  10586. PointLight.prototype.supportsVSM = function () {
  10587. return false;
  10588. };
  10589. PointLight.prototype.needRefreshPerFrame = function () {
  10590. return false;
  10591. };
  10592. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10593. switch (faceIndex) {
  10594. case 0:
  10595. return new BABYLON.Vector3(1, 0, 0);
  10596. case 1:
  10597. return new BABYLON.Vector3(-1, 0, 0);
  10598. case 2:
  10599. return new BABYLON.Vector3(0, -1, 0);
  10600. case 3:
  10601. return new BABYLON.Vector3(0, 1, 0);
  10602. case 4:
  10603. return new BABYLON.Vector3(0, 0, 1);
  10604. case 5:
  10605. return new BABYLON.Vector3(0, 0, -1);
  10606. }
  10607. return BABYLON.Vector3.Zero();
  10608. };
  10609. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10610. var activeCamera = this.getScene().activeCamera;
  10611. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10612. };
  10613. PointLight.prototype._getWorldMatrix = function () {
  10614. if (!this._worldMatrix) {
  10615. this._worldMatrix = BABYLON.Matrix.Identity();
  10616. }
  10617. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10618. return this._worldMatrix;
  10619. };
  10620. PointLight.prototype.getTypeID = function () {
  10621. return 0;
  10622. };
  10623. __decorate([
  10624. BABYLON.serializeAsVector3()
  10625. ], PointLight.prototype, "position", void 0);
  10626. return PointLight;
  10627. })(BABYLON.Light);
  10628. BABYLON.PointLight = PointLight;
  10629. })(BABYLON || (BABYLON = {}));
  10630. var BABYLON;
  10631. (function (BABYLON) {
  10632. var SpotLight = (function (_super) {
  10633. __extends(SpotLight, _super);
  10634. function SpotLight(name, position, direction, angle, exponent, scene) {
  10635. _super.call(this, name, scene);
  10636. this.position = position;
  10637. this.direction = direction;
  10638. this.angle = angle;
  10639. this.exponent = exponent;
  10640. }
  10641. SpotLight.prototype.getAbsolutePosition = function () {
  10642. return this.transformedPosition ? this.transformedPosition : this.position;
  10643. };
  10644. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10645. var activeCamera = this.getScene().activeCamera;
  10646. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  10647. };
  10648. SpotLight.prototype.needCube = function () {
  10649. return false;
  10650. };
  10651. SpotLight.prototype.supportsVSM = function () {
  10652. return true;
  10653. };
  10654. SpotLight.prototype.needRefreshPerFrame = function () {
  10655. return false;
  10656. };
  10657. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  10658. return this.direction;
  10659. };
  10660. SpotLight.prototype.setDirectionToTarget = function (target) {
  10661. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10662. return this.direction;
  10663. };
  10664. SpotLight.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. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  10675. var normalizeDirection;
  10676. if (this.parent && this.parent.getWorldMatrix) {
  10677. if (!this._transformedDirection) {
  10678. this._transformedDirection = BABYLON.Vector3.Zero();
  10679. }
  10680. this.computeTransformedPosition();
  10681. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10682. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  10683. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  10684. }
  10685. else {
  10686. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  10687. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10688. }
  10689. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  10690. };
  10691. SpotLight.prototype._getWorldMatrix = function () {
  10692. if (!this._worldMatrix) {
  10693. this._worldMatrix = BABYLON.Matrix.Identity();
  10694. }
  10695. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10696. return this._worldMatrix;
  10697. };
  10698. SpotLight.prototype.getTypeID = function () {
  10699. return 2;
  10700. };
  10701. __decorate([
  10702. BABYLON.serializeAsVector3()
  10703. ], SpotLight.prototype, "position", void 0);
  10704. __decorate([
  10705. BABYLON.serializeAsVector3()
  10706. ], SpotLight.prototype, "direction", void 0);
  10707. __decorate([
  10708. BABYLON.serialize()
  10709. ], SpotLight.prototype, "angle", void 0);
  10710. __decorate([
  10711. BABYLON.serialize()
  10712. ], SpotLight.prototype, "exponent", void 0);
  10713. return SpotLight;
  10714. })(BABYLON.Light);
  10715. BABYLON.SpotLight = SpotLight;
  10716. })(BABYLON || (BABYLON = {}));
  10717. var BABYLON;
  10718. (function (BABYLON) {
  10719. var HemisphericLight = (function (_super) {
  10720. __extends(HemisphericLight, _super);
  10721. function HemisphericLight(name, direction, scene) {
  10722. _super.call(this, name, scene);
  10723. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  10724. this.direction = direction;
  10725. }
  10726. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  10727. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  10728. return this.direction;
  10729. };
  10730. HemisphericLight.prototype.getShadowGenerator = function () {
  10731. return null;
  10732. };
  10733. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  10734. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  10735. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  10736. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  10737. };
  10738. HemisphericLight.prototype._getWorldMatrix = function () {
  10739. if (!this._worldMatrix) {
  10740. this._worldMatrix = BABYLON.Matrix.Identity();
  10741. }
  10742. return this._worldMatrix;
  10743. };
  10744. HemisphericLight.prototype.getTypeID = function () {
  10745. return 3;
  10746. };
  10747. __decorate([
  10748. BABYLON.serializeAsColor3()
  10749. ], HemisphericLight.prototype, "groundColor", void 0);
  10750. __decorate([
  10751. BABYLON.serializeAsVector3()
  10752. ], HemisphericLight.prototype, "direction", void 0);
  10753. return HemisphericLight;
  10754. })(BABYLON.Light);
  10755. BABYLON.HemisphericLight = HemisphericLight;
  10756. })(BABYLON || (BABYLON = {}));
  10757. var BABYLON;
  10758. (function (BABYLON) {
  10759. var DirectionalLight = (function (_super) {
  10760. __extends(DirectionalLight, _super);
  10761. function DirectionalLight(name, direction, scene) {
  10762. _super.call(this, name, scene);
  10763. this.shadowOrthoScale = 0.5;
  10764. this.autoUpdateExtends = true;
  10765. // Cache
  10766. this._orthoLeft = Number.MAX_VALUE;
  10767. this._orthoRight = Number.MIN_VALUE;
  10768. this._orthoTop = Number.MIN_VALUE;
  10769. this._orthoBottom = Number.MAX_VALUE;
  10770. this.position = direction.scale(-1);
  10771. this.direction = direction;
  10772. }
  10773. DirectionalLight.prototype.getAbsolutePosition = function () {
  10774. return this.transformedPosition ? this.transformedPosition : this.position;
  10775. };
  10776. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  10777. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  10778. return this.direction;
  10779. };
  10780. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10781. var activeCamera = this.getScene().activeCamera;
  10782. // Check extends
  10783. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  10784. var tempVector3 = BABYLON.Vector3.Zero();
  10785. this._orthoLeft = Number.MAX_VALUE;
  10786. this._orthoRight = Number.MIN_VALUE;
  10787. this._orthoTop = Number.MIN_VALUE;
  10788. this._orthoBottom = Number.MAX_VALUE;
  10789. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  10790. var mesh = renderList[meshIndex];
  10791. if (!mesh) {
  10792. continue;
  10793. }
  10794. var boundingInfo = mesh.getBoundingInfo();
  10795. if (!boundingInfo) {
  10796. continue;
  10797. }
  10798. var boundingBox = boundingInfo.boundingBox;
  10799. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  10800. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  10801. if (tempVector3.x < this._orthoLeft)
  10802. this._orthoLeft = tempVector3.x;
  10803. if (tempVector3.y < this._orthoBottom)
  10804. this._orthoBottom = tempVector3.y;
  10805. if (tempVector3.x > this._orthoRight)
  10806. this._orthoRight = tempVector3.x;
  10807. if (tempVector3.y > this._orthoTop)
  10808. this._orthoTop = tempVector3.y;
  10809. }
  10810. }
  10811. }
  10812. var xOffset = this._orthoRight - this._orthoLeft;
  10813. var yOffset = this._orthoTop - this._orthoBottom;
  10814. 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);
  10815. };
  10816. DirectionalLight.prototype.supportsVSM = function () {
  10817. return true;
  10818. };
  10819. DirectionalLight.prototype.needRefreshPerFrame = function () {
  10820. return true;
  10821. };
  10822. DirectionalLight.prototype.needCube = function () {
  10823. return false;
  10824. };
  10825. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  10826. return this.direction;
  10827. };
  10828. DirectionalLight.prototype.computeTransformedPosition = function () {
  10829. if (this.parent && this.parent.getWorldMatrix) {
  10830. if (!this.transformedPosition) {
  10831. this.transformedPosition = BABYLON.Vector3.Zero();
  10832. }
  10833. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10834. return true;
  10835. }
  10836. return false;
  10837. };
  10838. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  10839. if (this.parent && this.parent.getWorldMatrix) {
  10840. if (!this._transformedDirection) {
  10841. this._transformedDirection = BABYLON.Vector3.Zero();
  10842. }
  10843. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  10844. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  10845. return;
  10846. }
  10847. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  10848. };
  10849. DirectionalLight.prototype._getWorldMatrix = function () {
  10850. if (!this._worldMatrix) {
  10851. this._worldMatrix = BABYLON.Matrix.Identity();
  10852. }
  10853. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  10854. return this._worldMatrix;
  10855. };
  10856. DirectionalLight.prototype.getTypeID = function () {
  10857. return 1;
  10858. };
  10859. __decorate([
  10860. BABYLON.serializeAsVector3()
  10861. ], DirectionalLight.prototype, "position", void 0);
  10862. __decorate([
  10863. BABYLON.serializeAsVector3()
  10864. ], DirectionalLight.prototype, "direction", void 0);
  10865. __decorate([
  10866. BABYLON.serialize()
  10867. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  10868. __decorate([
  10869. BABYLON.serialize()
  10870. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  10871. return DirectionalLight;
  10872. })(BABYLON.Light);
  10873. BABYLON.DirectionalLight = DirectionalLight;
  10874. })(BABYLON || (BABYLON = {}));
  10875. var BABYLON;
  10876. (function (BABYLON) {
  10877. var ShadowGenerator = (function () {
  10878. function ShadowGenerator(mapSize, light) {
  10879. var _this = this;
  10880. // Members
  10881. this._filter = ShadowGenerator.FILTER_NONE;
  10882. this.blurScale = 2;
  10883. this._blurBoxOffset = 0;
  10884. this._bias = 0.00005;
  10885. this._lightDirection = BABYLON.Vector3.Zero();
  10886. this.forceBackFacesOnly = false;
  10887. this._darkness = 0;
  10888. this._transparencyShadow = false;
  10889. this._viewMatrix = BABYLON.Matrix.Zero();
  10890. this._projectionMatrix = BABYLON.Matrix.Zero();
  10891. this._transformMatrix = BABYLON.Matrix.Zero();
  10892. this._worldViewProjection = BABYLON.Matrix.Zero();
  10893. this._currentFaceIndex = 0;
  10894. this._currentFaceIndexCache = 0;
  10895. this._useFullFloat = true;
  10896. this._light = light;
  10897. this._scene = light.getScene();
  10898. this._mapSize = mapSize;
  10899. light._shadowGenerator = this;
  10900. // Texture type fallback from float to int if not supported.
  10901. var textureType;
  10902. var caps = this._scene.getEngine().getCaps();
  10903. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  10904. this._useFullFloat = true;
  10905. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  10906. }
  10907. else {
  10908. this._useFullFloat = false;
  10909. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  10910. }
  10911. // Render target
  10912. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  10913. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10914. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10915. this._shadowMap.anisotropicFilteringLevel = 1;
  10916. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10917. this._shadowMap.renderParticles = false;
  10918. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  10919. _this._currentFaceIndex = faceIndex;
  10920. });
  10921. this._shadowMap.onAfterUnbindObservable.add(function () {
  10922. if (!_this.useBlurVarianceShadowMap) {
  10923. return;
  10924. }
  10925. if (!_this._shadowMap2) {
  10926. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  10927. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10928. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  10929. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10930. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10931. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  10932. effect.setTexture("textureSampler", _this._shadowMap);
  10933. });
  10934. _this.blurBoxOffset = 1;
  10935. }
  10936. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10937. });
  10938. // Custom render function
  10939. var renderSubMesh = function (subMesh) {
  10940. var mesh = subMesh.getRenderingMesh();
  10941. var scene = _this._scene;
  10942. var engine = scene.getEngine();
  10943. // Culling
  10944. engine.setState(subMesh.getMaterial().backFaceCulling);
  10945. // Managing instances
  10946. var batch = mesh._getInstancesRenderList(subMesh._id);
  10947. if (batch.mustReturn) {
  10948. return;
  10949. }
  10950. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10951. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10952. engine.enableEffect(_this._effect);
  10953. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10954. var material = subMesh.getMaterial();
  10955. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10956. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10957. if (_this.getLight().needCube()) {
  10958. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10959. }
  10960. // Alpha test
  10961. if (material && material.needAlphaTesting()) {
  10962. var alphaTexture = material.getAlphaTestTexture();
  10963. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10964. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10965. }
  10966. // Bones
  10967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10968. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10969. }
  10970. if (_this.forceBackFacesOnly) {
  10971. engine.setState(true, 0, false, true);
  10972. }
  10973. // Draw
  10974. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10975. if (_this.forceBackFacesOnly) {
  10976. engine.setState(true, 0, false, false);
  10977. }
  10978. }
  10979. else {
  10980. // Need to reset refresh rate of the shadowMap
  10981. _this._shadowMap.resetRefreshCounter();
  10982. }
  10983. };
  10984. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10985. var index;
  10986. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10987. renderSubMesh(opaqueSubMeshes.data[index]);
  10988. }
  10989. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10990. renderSubMesh(alphaTestSubMeshes.data[index]);
  10991. }
  10992. if (_this._transparencyShadow) {
  10993. for (index = 0; index < transparentSubMeshes.length; index++) {
  10994. renderSubMesh(transparentSubMeshes.data[index]);
  10995. }
  10996. }
  10997. };
  10998. this._shadowMap.onClearObservable.add(function (engine) {
  10999. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11000. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  11001. }
  11002. else {
  11003. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  11004. }
  11005. });
  11006. }
  11007. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11008. // Static
  11009. get: function () {
  11010. return ShadowGenerator._FILTER_NONE;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11016. get: function () {
  11017. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11023. get: function () {
  11024. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11030. get: function () {
  11031. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11037. get: function () {
  11038. return this._bias;
  11039. },
  11040. set: function (bias) {
  11041. this._bias = bias;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11047. get: function () {
  11048. return this._blurBoxOffset;
  11049. },
  11050. set: function (value) {
  11051. var _this = this;
  11052. if (this._blurBoxOffset === value) {
  11053. return;
  11054. }
  11055. this._blurBoxOffset = value;
  11056. if (this._boxBlurPostprocess) {
  11057. this._boxBlurPostprocess.dispose();
  11058. }
  11059. 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);
  11060. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11061. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11062. });
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11068. get: function () {
  11069. return this._filter;
  11070. },
  11071. set: function (value) {
  11072. if (this._filter === value) {
  11073. return;
  11074. }
  11075. this._filter = value;
  11076. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11077. this._shadowMap.anisotropicFilteringLevel = 16;
  11078. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11079. }
  11080. else {
  11081. this._shadowMap.anisotropicFilteringLevel = 1;
  11082. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11083. }
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11089. get: function () {
  11090. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11091. },
  11092. set: function (value) {
  11093. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11099. get: function () {
  11100. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11101. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11102. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11103. },
  11104. set: function (value) {
  11105. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11106. },
  11107. enumerable: true,
  11108. configurable: true
  11109. });
  11110. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11111. get: function () {
  11112. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11113. },
  11114. set: function (value) {
  11115. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11121. var defines = [];
  11122. if (this._useFullFloat) {
  11123. defines.push("#define FULLFLOAT");
  11124. }
  11125. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11126. defines.push("#define VSM");
  11127. }
  11128. if (this.getLight().needCube()) {
  11129. defines.push("#define CUBEMAP");
  11130. }
  11131. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11132. var mesh = subMesh.getMesh();
  11133. var material = subMesh.getMaterial();
  11134. // Alpha test
  11135. if (material && material.needAlphaTesting()) {
  11136. defines.push("#define ALPHATEST");
  11137. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11138. attribs.push(BABYLON.VertexBuffer.UVKind);
  11139. defines.push("#define UV1");
  11140. }
  11141. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11142. var alphaTexture = material.getAlphaTestTexture();
  11143. if (alphaTexture.coordinatesIndex === 1) {
  11144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11145. defines.push("#define UV2");
  11146. }
  11147. }
  11148. }
  11149. // Bones
  11150. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11151. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11152. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11153. if (mesh.numBoneInfluencers > 4) {
  11154. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11155. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11156. }
  11157. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11158. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11159. }
  11160. else {
  11161. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11162. }
  11163. // Instances
  11164. if (useInstances) {
  11165. defines.push("#define INSTANCES");
  11166. attribs.push("world0");
  11167. attribs.push("world1");
  11168. attribs.push("world2");
  11169. attribs.push("world3");
  11170. }
  11171. // Get correct effect
  11172. var join = defines.join("\n");
  11173. if (this._cachedDefines !== join) {
  11174. this._cachedDefines = join;
  11175. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11176. }
  11177. return this._effect.isReady();
  11178. };
  11179. ShadowGenerator.prototype.getShadowMap = function () {
  11180. return this._shadowMap;
  11181. };
  11182. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11183. if (this._shadowMap2) {
  11184. return this._shadowMap2;
  11185. }
  11186. return this._shadowMap;
  11187. };
  11188. ShadowGenerator.prototype.getLight = function () {
  11189. return this._light;
  11190. };
  11191. // Methods
  11192. ShadowGenerator.prototype.getTransformMatrix = function () {
  11193. var scene = this._scene;
  11194. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11195. return this._transformMatrix;
  11196. }
  11197. this._currentRenderID = scene.getRenderId();
  11198. this._currentFaceIndexCache = this._currentFaceIndex;
  11199. var lightPosition = this._light.position;
  11200. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11201. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11202. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11203. }
  11204. if (this._light.computeTransformedPosition()) {
  11205. lightPosition = this._light.transformedPosition;
  11206. }
  11207. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11208. this._cachedPosition = lightPosition.clone();
  11209. this._cachedDirection = this._lightDirection.clone();
  11210. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11211. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11212. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11213. }
  11214. return this._transformMatrix;
  11215. };
  11216. ShadowGenerator.prototype.getDarkness = function () {
  11217. return this._darkness;
  11218. };
  11219. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11220. if (darkness >= 1.0)
  11221. this._darkness = 1.0;
  11222. else if (darkness <= 0.0)
  11223. this._darkness = 0.0;
  11224. else
  11225. this._darkness = darkness;
  11226. };
  11227. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11228. this._transparencyShadow = hasShadow;
  11229. };
  11230. ShadowGenerator.prototype._packHalf = function (depth) {
  11231. var scale = depth * 255.0;
  11232. var fract = scale - Math.floor(scale);
  11233. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11234. };
  11235. ShadowGenerator.prototype.dispose = function () {
  11236. this._shadowMap.dispose();
  11237. if (this._shadowMap2) {
  11238. this._shadowMap2.dispose();
  11239. }
  11240. if (this._downSamplePostprocess) {
  11241. this._downSamplePostprocess.dispose();
  11242. }
  11243. if (this._boxBlurPostprocess) {
  11244. this._boxBlurPostprocess.dispose();
  11245. }
  11246. };
  11247. ShadowGenerator.prototype.serialize = function () {
  11248. var serializationObject = {};
  11249. serializationObject.lightId = this._light.id;
  11250. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11251. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11252. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11253. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11254. serializationObject.renderList = [];
  11255. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11256. var mesh = this.getShadowMap().renderList[meshIndex];
  11257. serializationObject.renderList.push(mesh.id);
  11258. }
  11259. return serializationObject;
  11260. };
  11261. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11262. //casting to point light, as light is missing the position attr and typescript complains.
  11263. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11264. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11265. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11266. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11267. meshes.forEach(function (mesh) {
  11268. shadowGenerator.getShadowMap().renderList.push(mesh);
  11269. });
  11270. }
  11271. if (parsedShadowGenerator.usePoissonSampling) {
  11272. shadowGenerator.usePoissonSampling = true;
  11273. }
  11274. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11275. shadowGenerator.useVarianceShadowMap = true;
  11276. }
  11277. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11278. shadowGenerator.useBlurVarianceShadowMap = true;
  11279. if (parsedShadowGenerator.blurScale) {
  11280. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11281. }
  11282. if (parsedShadowGenerator.blurBoxOffset) {
  11283. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11284. }
  11285. }
  11286. if (parsedShadowGenerator.bias !== undefined) {
  11287. shadowGenerator.bias = parsedShadowGenerator.bias;
  11288. }
  11289. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11290. return shadowGenerator;
  11291. };
  11292. ShadowGenerator._FILTER_NONE = 0;
  11293. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11294. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11295. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11296. return ShadowGenerator;
  11297. })();
  11298. BABYLON.ShadowGenerator = ShadowGenerator;
  11299. })(BABYLON || (BABYLON = {}));
  11300. var BABYLON;
  11301. (function (BABYLON) {
  11302. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11303. if (boxMin.x > sphereCenter.x + sphereRadius)
  11304. return false;
  11305. if (sphereCenter.x - sphereRadius > boxMax.x)
  11306. return false;
  11307. if (boxMin.y > sphereCenter.y + sphereRadius)
  11308. return false;
  11309. if (sphereCenter.y - sphereRadius > boxMax.y)
  11310. return false;
  11311. if (boxMin.z > sphereCenter.z + sphereRadius)
  11312. return false;
  11313. if (sphereCenter.z - sphereRadius > boxMax.z)
  11314. return false;
  11315. return true;
  11316. };
  11317. var getLowestRoot = (function () {
  11318. var result = { root: 0, found: false };
  11319. return function (a, b, c, maxR) {
  11320. result.root = 0;
  11321. result.found = false;
  11322. var determinant = b * b - 4.0 * a * c;
  11323. if (determinant < 0)
  11324. return result;
  11325. var sqrtD = Math.sqrt(determinant);
  11326. var r1 = (-b - sqrtD) / (2.0 * a);
  11327. var r2 = (-b + sqrtD) / (2.0 * a);
  11328. if (r1 > r2) {
  11329. var temp = r2;
  11330. r2 = r1;
  11331. r1 = temp;
  11332. }
  11333. if (r1 > 0 && r1 < maxR) {
  11334. result.root = r1;
  11335. result.found = true;
  11336. return result;
  11337. }
  11338. if (r2 > 0 && r2 < maxR) {
  11339. result.root = r2;
  11340. result.found = true;
  11341. return result;
  11342. }
  11343. return result;
  11344. };
  11345. })();
  11346. var Collider = (function () {
  11347. function Collider() {
  11348. this.radius = new BABYLON.Vector3(1, 1, 1);
  11349. this.retry = 0;
  11350. this.basePointWorld = BABYLON.Vector3.Zero();
  11351. this.velocityWorld = BABYLON.Vector3.Zero();
  11352. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11353. this._collisionPoint = BABYLON.Vector3.Zero();
  11354. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11355. this._tempVector = BABYLON.Vector3.Zero();
  11356. this._tempVector2 = BABYLON.Vector3.Zero();
  11357. this._tempVector3 = BABYLON.Vector3.Zero();
  11358. this._tempVector4 = BABYLON.Vector3.Zero();
  11359. this._edge = BABYLON.Vector3.Zero();
  11360. this._baseToVertex = BABYLON.Vector3.Zero();
  11361. this._destinationPoint = BABYLON.Vector3.Zero();
  11362. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11363. this._displacementVector = BABYLON.Vector3.Zero();
  11364. }
  11365. // Methods
  11366. Collider.prototype._initialize = function (source, dir, e) {
  11367. this.velocity = dir;
  11368. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11369. this.basePoint = source;
  11370. source.multiplyToRef(this.radius, this.basePointWorld);
  11371. dir.multiplyToRef(this.radius, this.velocityWorld);
  11372. this.velocityWorldLength = this.velocityWorld.length();
  11373. this.epsilon = e;
  11374. this.collisionFound = false;
  11375. };
  11376. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11377. pa.subtractToRef(point, this._tempVector);
  11378. pb.subtractToRef(point, this._tempVector2);
  11379. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11380. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11381. if (d < 0)
  11382. return false;
  11383. pc.subtractToRef(point, this._tempVector3);
  11384. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11385. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11386. if (d < 0)
  11387. return false;
  11388. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11389. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11390. return d >= 0;
  11391. };
  11392. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11393. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11394. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11395. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11396. return false;
  11397. }
  11398. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11399. return false;
  11400. return true;
  11401. };
  11402. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11403. var t0;
  11404. var embeddedInPlane = false;
  11405. //defensive programming, actually not needed.
  11406. if (!trianglePlaneArray) {
  11407. trianglePlaneArray = [];
  11408. }
  11409. if (!trianglePlaneArray[faceIndex]) {
  11410. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11411. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11412. }
  11413. var trianglePlane = trianglePlaneArray[faceIndex];
  11414. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11415. return;
  11416. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11417. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11418. if (normalDotVelocity == 0) {
  11419. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11420. return;
  11421. embeddedInPlane = true;
  11422. t0 = 0;
  11423. }
  11424. else {
  11425. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11426. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11427. if (t0 > t1) {
  11428. var temp = t1;
  11429. t1 = t0;
  11430. t0 = temp;
  11431. }
  11432. if (t0 > 1.0 || t1 < 0.0)
  11433. return;
  11434. if (t0 < 0)
  11435. t0 = 0;
  11436. if (t0 > 1.0)
  11437. t0 = 1.0;
  11438. }
  11439. this._collisionPoint.copyFromFloats(0, 0, 0);
  11440. var found = false;
  11441. var t = 1.0;
  11442. if (!embeddedInPlane) {
  11443. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11444. this.velocity.scaleToRef(t0, this._tempVector);
  11445. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11446. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11447. found = true;
  11448. t = t0;
  11449. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11450. }
  11451. }
  11452. if (!found) {
  11453. var velocitySquaredLength = this.velocity.lengthSquared();
  11454. var a = velocitySquaredLength;
  11455. this.basePoint.subtractToRef(p1, this._tempVector);
  11456. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11457. var c = this._tempVector.lengthSquared() - 1.0;
  11458. var lowestRoot = getLowestRoot(a, b, c, t);
  11459. if (lowestRoot.found) {
  11460. t = lowestRoot.root;
  11461. found = true;
  11462. this._collisionPoint.copyFrom(p1);
  11463. }
  11464. this.basePoint.subtractToRef(p2, this._tempVector);
  11465. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11466. c = this._tempVector.lengthSquared() - 1.0;
  11467. lowestRoot = getLowestRoot(a, b, c, t);
  11468. if (lowestRoot.found) {
  11469. t = lowestRoot.root;
  11470. found = true;
  11471. this._collisionPoint.copyFrom(p2);
  11472. }
  11473. this.basePoint.subtractToRef(p3, this._tempVector);
  11474. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11475. c = this._tempVector.lengthSquared() - 1.0;
  11476. lowestRoot = getLowestRoot(a, b, c, t);
  11477. if (lowestRoot.found) {
  11478. t = lowestRoot.root;
  11479. found = true;
  11480. this._collisionPoint.copyFrom(p3);
  11481. }
  11482. p2.subtractToRef(p1, this._edge);
  11483. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11484. var edgeSquaredLength = this._edge.lengthSquared();
  11485. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11486. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11487. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11488. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11489. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11490. lowestRoot = getLowestRoot(a, b, c, t);
  11491. if (lowestRoot.found) {
  11492. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11493. if (f >= 0.0 && f <= 1.0) {
  11494. t = lowestRoot.root;
  11495. found = true;
  11496. this._edge.scaleInPlace(f);
  11497. p1.addToRef(this._edge, this._collisionPoint);
  11498. }
  11499. }
  11500. p3.subtractToRef(p2, this._edge);
  11501. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11502. edgeSquaredLength = this._edge.lengthSquared();
  11503. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11504. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11505. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11506. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11507. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11508. lowestRoot = getLowestRoot(a, b, c, t);
  11509. if (lowestRoot.found) {
  11510. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11511. if (f >= 0.0 && f <= 1.0) {
  11512. t = lowestRoot.root;
  11513. found = true;
  11514. this._edge.scaleInPlace(f);
  11515. p2.addToRef(this._edge, this._collisionPoint);
  11516. }
  11517. }
  11518. p1.subtractToRef(p3, this._edge);
  11519. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11520. edgeSquaredLength = this._edge.lengthSquared();
  11521. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11522. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11523. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11524. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11525. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11526. lowestRoot = getLowestRoot(a, b, c, t);
  11527. if (lowestRoot.found) {
  11528. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11529. if (f >= 0.0 && f <= 1.0) {
  11530. t = lowestRoot.root;
  11531. found = true;
  11532. this._edge.scaleInPlace(f);
  11533. p3.addToRef(this._edge, this._collisionPoint);
  11534. }
  11535. }
  11536. }
  11537. if (found) {
  11538. var distToCollision = t * this.velocity.length();
  11539. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11540. if (!this.intersectionPoint) {
  11541. this.intersectionPoint = this._collisionPoint.clone();
  11542. }
  11543. else {
  11544. this.intersectionPoint.copyFrom(this._collisionPoint);
  11545. }
  11546. this.nearestDistance = distToCollision;
  11547. this.collisionFound = true;
  11548. }
  11549. }
  11550. };
  11551. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11552. for (var i = indexStart; i < indexEnd; i += 3) {
  11553. var p1 = pts[indices[i] - decal];
  11554. var p2 = pts[indices[i + 1] - decal];
  11555. var p3 = pts[indices[i + 2] - decal];
  11556. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11557. }
  11558. };
  11559. Collider.prototype._getResponse = function (pos, vel) {
  11560. pos.addToRef(vel, this._destinationPoint);
  11561. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11562. this.basePoint.addToRef(vel, pos);
  11563. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11564. this._slidePlaneNormal.normalize();
  11565. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11566. pos.addInPlace(this._displacementVector);
  11567. this.intersectionPoint.addInPlace(this._displacementVector);
  11568. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11569. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11570. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11571. };
  11572. return Collider;
  11573. })();
  11574. BABYLON.Collider = Collider;
  11575. })(BABYLON || (BABYLON = {}));
  11576. var BABYLON;
  11577. (function (BABYLON) {
  11578. //WebWorker code will be inserted to this variable.
  11579. BABYLON.CollisionWorker = "";
  11580. (function (WorkerTaskType) {
  11581. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11582. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11583. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11584. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11585. var WorkerTaskType = BABYLON.WorkerTaskType;
  11586. (function (WorkerReplyType) {
  11587. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11588. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11589. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11590. var WorkerReplyType = BABYLON.WorkerReplyType;
  11591. var CollisionCoordinatorWorker = (function () {
  11592. function CollisionCoordinatorWorker() {
  11593. var _this = this;
  11594. this._scaledPosition = BABYLON.Vector3.Zero();
  11595. this._scaledVelocity = BABYLON.Vector3.Zero();
  11596. this.onMeshUpdated = function (mesh) {
  11597. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11598. };
  11599. this.onGeometryUpdated = function (geometry) {
  11600. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11601. };
  11602. this._afterRender = function () {
  11603. if (!_this._init)
  11604. return;
  11605. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11606. return;
  11607. }
  11608. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11609. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11610. if (_this._runningUpdated > 4) {
  11611. return;
  11612. }
  11613. ++_this._runningUpdated;
  11614. var payload = {
  11615. updatedMeshes: _this._addUpdateMeshesList,
  11616. updatedGeometries: _this._addUpdateGeometriesList,
  11617. removedGeometries: _this._toRemoveGeometryArray,
  11618. removedMeshes: _this._toRemoveMeshesArray
  11619. };
  11620. var message = {
  11621. payload: payload,
  11622. taskType: WorkerTaskType.UPDATE
  11623. };
  11624. var serializable = [];
  11625. for (var id in payload.updatedGeometries) {
  11626. if (payload.updatedGeometries.hasOwnProperty(id)) {
  11627. //prepare transferables
  11628. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  11629. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  11630. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  11631. }
  11632. }
  11633. _this._worker.postMessage(message, serializable);
  11634. _this._addUpdateMeshesList = {};
  11635. _this._addUpdateGeometriesList = {};
  11636. _this._toRemoveGeometryArray = [];
  11637. _this._toRemoveMeshesArray = [];
  11638. };
  11639. this._onMessageFromWorker = function (e) {
  11640. var returnData = e.data;
  11641. if (returnData.error != WorkerReplyType.SUCCESS) {
  11642. //TODO what errors can be returned from the worker?
  11643. BABYLON.Tools.Warn("error returned from worker!");
  11644. return;
  11645. }
  11646. switch (returnData.taskType) {
  11647. case WorkerTaskType.INIT:
  11648. _this._init = true;
  11649. //Update the worked with ALL of the scene's current state
  11650. _this._scene.meshes.forEach(function (mesh) {
  11651. _this.onMeshAdded(mesh);
  11652. });
  11653. _this._scene.getGeometries().forEach(function (geometry) {
  11654. _this.onGeometryAdded(geometry);
  11655. });
  11656. break;
  11657. case WorkerTaskType.UPDATE:
  11658. _this._runningUpdated--;
  11659. break;
  11660. case WorkerTaskType.COLLIDE:
  11661. _this._runningCollisionTask = false;
  11662. var returnPayload = returnData.payload;
  11663. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  11664. return;
  11665. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  11666. //cleanup
  11667. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  11668. break;
  11669. }
  11670. };
  11671. this._collisionsCallbackArray = [];
  11672. this._init = false;
  11673. this._runningUpdated = 0;
  11674. this._runningCollisionTask = false;
  11675. this._addUpdateMeshesList = {};
  11676. this._addUpdateGeometriesList = {};
  11677. this._toRemoveGeometryArray = [];
  11678. this._toRemoveMeshesArray = [];
  11679. }
  11680. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11681. if (!this._init)
  11682. return;
  11683. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  11684. return;
  11685. position.divideToRef(collider.radius, this._scaledPosition);
  11686. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11687. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  11688. var payload = {
  11689. collider: {
  11690. position: this._scaledPosition.asArray(),
  11691. velocity: this._scaledVelocity.asArray(),
  11692. radius: collider.radius.asArray()
  11693. },
  11694. collisionId: collisionIndex,
  11695. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  11696. maximumRetry: maximumRetry
  11697. };
  11698. var message = {
  11699. payload: payload,
  11700. taskType: WorkerTaskType.COLLIDE
  11701. };
  11702. this._worker.postMessage(message);
  11703. };
  11704. CollisionCoordinatorWorker.prototype.init = function (scene) {
  11705. this._scene = scene;
  11706. this._scene.registerAfterRender(this._afterRender);
  11707. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  11708. this._worker = new Worker(workerUrl);
  11709. this._worker.onmessage = this._onMessageFromWorker;
  11710. var message = {
  11711. payload: {},
  11712. taskType: WorkerTaskType.INIT
  11713. };
  11714. this._worker.postMessage(message);
  11715. };
  11716. CollisionCoordinatorWorker.prototype.destroy = function () {
  11717. this._scene.unregisterAfterRender(this._afterRender);
  11718. this._worker.terminate();
  11719. };
  11720. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  11721. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  11722. this.onMeshUpdated(mesh);
  11723. };
  11724. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  11725. this._toRemoveMeshesArray.push(mesh.uniqueId);
  11726. };
  11727. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  11728. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  11729. geometry.onGeometryUpdated = this.onGeometryUpdated;
  11730. this.onGeometryUpdated(geometry);
  11731. };
  11732. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  11733. this._toRemoveGeometryArray.push(geometry.id);
  11734. };
  11735. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  11736. var submeshes = [];
  11737. if (mesh.subMeshes) {
  11738. submeshes = mesh.subMeshes.map(function (sm, idx) {
  11739. return {
  11740. position: idx,
  11741. verticesStart: sm.verticesStart,
  11742. verticesCount: sm.verticesCount,
  11743. indexStart: sm.indexStart,
  11744. indexCount: sm.indexCount,
  11745. hasMaterial: !!sm.getMaterial(),
  11746. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11747. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  11748. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11749. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  11750. };
  11751. });
  11752. }
  11753. var geometryId = null;
  11754. if (mesh instanceof BABYLON.Mesh) {
  11755. geometryId = mesh.geometry ? mesh.geometry.id : null;
  11756. }
  11757. else if (mesh instanceof BABYLON.InstancedMesh) {
  11758. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  11759. }
  11760. return {
  11761. uniqueId: mesh.uniqueId,
  11762. id: mesh.id,
  11763. name: mesh.name,
  11764. geometryId: geometryId,
  11765. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  11766. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  11767. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  11768. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  11769. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  11770. subMeshes: submeshes,
  11771. checkCollisions: mesh.checkCollisions
  11772. };
  11773. };
  11774. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  11775. return {
  11776. id: geometry.id,
  11777. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  11778. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  11779. indices: new Int32Array(geometry.getIndices() || []),
  11780. };
  11781. };
  11782. return CollisionCoordinatorWorker;
  11783. })();
  11784. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  11785. var CollisionCoordinatorLegacy = (function () {
  11786. function CollisionCoordinatorLegacy() {
  11787. this._scaledPosition = BABYLON.Vector3.Zero();
  11788. this._scaledVelocity = BABYLON.Vector3.Zero();
  11789. this._finalPosition = BABYLON.Vector3.Zero();
  11790. }
  11791. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  11792. position.divideToRef(collider.radius, this._scaledPosition);
  11793. velocity.divideToRef(collider.radius, this._scaledVelocity);
  11794. collider.collidedMesh = null;
  11795. collider.retry = 0;
  11796. collider.initialVelocity = this._scaledVelocity;
  11797. collider.initialPosition = this._scaledPosition;
  11798. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  11799. this._finalPosition.multiplyInPlace(collider.radius);
  11800. //run the callback
  11801. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  11802. };
  11803. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  11804. this._scene = scene;
  11805. };
  11806. CollisionCoordinatorLegacy.prototype.destroy = function () {
  11807. //Legacy need no destruction method.
  11808. };
  11809. //No update in legacy mode
  11810. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  11811. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  11812. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  11813. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  11814. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  11815. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  11816. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  11817. if (excludedMesh === void 0) { excludedMesh = null; }
  11818. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  11819. if (collider.retry >= maximumRetry) {
  11820. finalPosition.copyFrom(position);
  11821. return;
  11822. }
  11823. collider._initialize(position, velocity, closeDistance);
  11824. // Check all meshes
  11825. for (var index = 0; index < this._scene.meshes.length; index++) {
  11826. var mesh = this._scene.meshes[index];
  11827. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  11828. mesh._checkCollision(collider);
  11829. }
  11830. }
  11831. if (!collider.collisionFound) {
  11832. position.addToRef(velocity, finalPosition);
  11833. return;
  11834. }
  11835. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  11836. collider._getResponse(position, velocity);
  11837. }
  11838. if (velocity.length() <= closeDistance) {
  11839. finalPosition.copyFrom(position);
  11840. return;
  11841. }
  11842. collider.retry++;
  11843. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  11844. };
  11845. return CollisionCoordinatorLegacy;
  11846. })();
  11847. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  11848. })(BABYLON || (BABYLON = {}));
  11849. var BABYLON;
  11850. (function (BABYLON) {
  11851. var Camera = (function (_super) {
  11852. __extends(Camera, _super);
  11853. function Camera(name, position, scene) {
  11854. _super.call(this, name, scene);
  11855. this.upVector = BABYLON.Vector3.Up();
  11856. this.orthoLeft = null;
  11857. this.orthoRight = null;
  11858. this.orthoBottom = null;
  11859. this.orthoTop = null;
  11860. this.fov = 0.8;
  11861. this.minZ = 1.0;
  11862. this.maxZ = 10000.0;
  11863. this.inertia = 0.9;
  11864. this.mode = Camera.PERSPECTIVE_CAMERA;
  11865. this.isIntermediate = false;
  11866. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  11867. this.layerMask = 0x0FFFFFFF;
  11868. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  11869. // Camera rig members
  11870. this.cameraRigMode = Camera.RIG_MODE_NONE;
  11871. this._rigCameras = new Array();
  11872. // Cache
  11873. this._computedViewMatrix = BABYLON.Matrix.Identity();
  11874. this._projectionMatrix = new BABYLON.Matrix();
  11875. this._postProcesses = new Array();
  11876. this._transformMatrix = BABYLON.Matrix.Zero();
  11877. this._activeMeshes = new BABYLON.SmartArray(256);
  11878. this._globalPosition = BABYLON.Vector3.Zero();
  11879. this._refreshFrustumPlanes = true;
  11880. scene.addCamera(this);
  11881. if (!scene.activeCamera) {
  11882. scene.activeCamera = this;
  11883. }
  11884. this.position = position;
  11885. }
  11886. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  11887. get: function () {
  11888. return Camera._PERSPECTIVE_CAMERA;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  11894. get: function () {
  11895. return Camera._ORTHOGRAPHIC_CAMERA;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  11901. get: function () {
  11902. return Camera._FOVMODE_VERTICAL_FIXED;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  11908. get: function () {
  11909. return Camera._FOVMODE_HORIZONTAL_FIXED;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  11915. get: function () {
  11916. return Camera._RIG_MODE_NONE;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  11922. get: function () {
  11923. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  11929. get: function () {
  11930. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  11936. get: function () {
  11937. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  11938. },
  11939. enumerable: true,
  11940. configurable: true
  11941. });
  11942. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11943. get: function () {
  11944. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11950. get: function () {
  11951. return Camera._RIG_MODE_VR;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. /**
  11957. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11958. */
  11959. Camera.prototype.toString = function (fullDetails) {
  11960. var ret = "Name: " + this.name;
  11961. ret += ", type: " + this.getTypeName();
  11962. if (this.animations) {
  11963. for (var i = 0; i < this.animations.length; i++) {
  11964. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11965. }
  11966. }
  11967. if (fullDetails) {
  11968. }
  11969. return ret;
  11970. };
  11971. Object.defineProperty(Camera.prototype, "globalPosition", {
  11972. get: function () {
  11973. return this._globalPosition;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Camera.prototype.getActiveMeshes = function () {
  11979. return this._activeMeshes;
  11980. };
  11981. Camera.prototype.isActiveMesh = function (mesh) {
  11982. return (this._activeMeshes.indexOf(mesh) !== -1);
  11983. };
  11984. //Cache
  11985. Camera.prototype._initCache = function () {
  11986. _super.prototype._initCache.call(this);
  11987. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11988. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11989. this._cache.mode = undefined;
  11990. this._cache.minZ = undefined;
  11991. this._cache.maxZ = undefined;
  11992. this._cache.fov = undefined;
  11993. this._cache.aspectRatio = undefined;
  11994. this._cache.orthoLeft = undefined;
  11995. this._cache.orthoRight = undefined;
  11996. this._cache.orthoBottom = undefined;
  11997. this._cache.orthoTop = undefined;
  11998. this._cache.renderWidth = undefined;
  11999. this._cache.renderHeight = undefined;
  12000. };
  12001. Camera.prototype._updateCache = function (ignoreParentClass) {
  12002. if (!ignoreParentClass) {
  12003. _super.prototype._updateCache.call(this);
  12004. }
  12005. var engine = this.getEngine();
  12006. this._cache.position.copyFrom(this.position);
  12007. this._cache.upVector.copyFrom(this.upVector);
  12008. this._cache.mode = this.mode;
  12009. this._cache.minZ = this.minZ;
  12010. this._cache.maxZ = this.maxZ;
  12011. this._cache.fov = this.fov;
  12012. this._cache.aspectRatio = engine.getAspectRatio(this);
  12013. this._cache.orthoLeft = this.orthoLeft;
  12014. this._cache.orthoRight = this.orthoRight;
  12015. this._cache.orthoBottom = this.orthoBottom;
  12016. this._cache.orthoTop = this.orthoTop;
  12017. this._cache.renderWidth = engine.getRenderWidth();
  12018. this._cache.renderHeight = engine.getRenderHeight();
  12019. };
  12020. Camera.prototype._updateFromScene = function () {
  12021. this.updateCache();
  12022. this.update();
  12023. };
  12024. // Synchronized
  12025. Camera.prototype._isSynchronized = function () {
  12026. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12027. };
  12028. Camera.prototype._isSynchronizedViewMatrix = function () {
  12029. if (!_super.prototype._isSynchronized.call(this))
  12030. return false;
  12031. return this._cache.position.equals(this.position)
  12032. && this._cache.upVector.equals(this.upVector)
  12033. && this.isSynchronizedWithParent();
  12034. };
  12035. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12036. var check = this._cache.mode === this.mode
  12037. && this._cache.minZ === this.minZ
  12038. && this._cache.maxZ === this.maxZ;
  12039. if (!check) {
  12040. return false;
  12041. }
  12042. var engine = this.getEngine();
  12043. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12044. check = this._cache.fov === this.fov
  12045. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12046. }
  12047. else {
  12048. check = this._cache.orthoLeft === this.orthoLeft
  12049. && this._cache.orthoRight === this.orthoRight
  12050. && this._cache.orthoBottom === this.orthoBottom
  12051. && this._cache.orthoTop === this.orthoTop
  12052. && this._cache.renderWidth === engine.getRenderWidth()
  12053. && this._cache.renderHeight === engine.getRenderHeight();
  12054. }
  12055. return check;
  12056. };
  12057. // Controls
  12058. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12059. };
  12060. Camera.prototype.detachControl = function (element) {
  12061. };
  12062. Camera.prototype.update = function () {
  12063. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12064. this._updateRigCameras();
  12065. }
  12066. this._checkInputs();
  12067. };
  12068. Camera.prototype._checkInputs = function () {
  12069. };
  12070. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12071. // invalidate framebuffer
  12072. if (this._postProcesses.length > 0) {
  12073. this._postProcesses[0].markTextureDirty();
  12074. }
  12075. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12076. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12077. var cam = this._rigCameras[i];
  12078. var rigPostProcess = cam._rigPostProcess;
  12079. // for VR rig, there does not have to be a post process
  12080. if (rigPostProcess) {
  12081. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12082. if (isPass) {
  12083. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12084. cam.isIntermediate = this._postProcesses.length === 0;
  12085. }
  12086. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12087. rigPostProcess.markTextureDirty();
  12088. }
  12089. else {
  12090. cam._postProcesses = this._postProcesses.slice(0);
  12091. }
  12092. }
  12093. };
  12094. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12095. if (insertAt === void 0) { insertAt = null; }
  12096. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12097. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12098. return 0;
  12099. }
  12100. if (insertAt == null || insertAt < 0) {
  12101. this._postProcesses.push(postProcess);
  12102. }
  12103. else {
  12104. this._postProcesses.splice(insertAt, 0, postProcess);
  12105. }
  12106. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12107. return this._postProcesses.indexOf(postProcess);
  12108. };
  12109. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12110. if (atIndices === void 0) { atIndices = null; }
  12111. var result = [];
  12112. var i;
  12113. var index;
  12114. if (!atIndices) {
  12115. var idx = this._postProcesses.indexOf(postProcess);
  12116. if (idx !== -1) {
  12117. this._postProcesses.splice(idx, 1);
  12118. }
  12119. }
  12120. else {
  12121. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12122. // iterate descending, so can just splice as we go
  12123. for (i = atIndices.length - 1; i >= 0; i--) {
  12124. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12125. result.push(i);
  12126. continue;
  12127. }
  12128. this._postProcesses.splice(index, 1);
  12129. }
  12130. }
  12131. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12132. return result;
  12133. };
  12134. Camera.prototype.getWorldMatrix = function () {
  12135. if (!this._worldMatrix) {
  12136. this._worldMatrix = BABYLON.Matrix.Identity();
  12137. }
  12138. var viewMatrix = this.getViewMatrix();
  12139. viewMatrix.invertToRef(this._worldMatrix);
  12140. return this._worldMatrix;
  12141. };
  12142. Camera.prototype._getViewMatrix = function () {
  12143. return BABYLON.Matrix.Identity();
  12144. };
  12145. Camera.prototype.getViewMatrix = function (force) {
  12146. this._computedViewMatrix = this._computeViewMatrix(force);
  12147. if (!force && this._isSynchronizedViewMatrix()) {
  12148. return this._computedViewMatrix;
  12149. }
  12150. this._refreshFrustumPlanes = true;
  12151. if (!this.parent || !this.parent.getWorldMatrix) {
  12152. this._globalPosition.copyFrom(this.position);
  12153. }
  12154. else {
  12155. if (!this._worldMatrix) {
  12156. this._worldMatrix = BABYLON.Matrix.Identity();
  12157. }
  12158. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12159. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12160. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12161. this._computedViewMatrix.invert();
  12162. this._markSyncedWithParent();
  12163. }
  12164. this._currentRenderId = this.getScene().getRenderId();
  12165. return this._computedViewMatrix;
  12166. };
  12167. Camera.prototype._computeViewMatrix = function (force) {
  12168. if (!force && this._isSynchronizedViewMatrix()) {
  12169. return this._computedViewMatrix;
  12170. }
  12171. this._computedViewMatrix = this._getViewMatrix();
  12172. this._currentRenderId = this.getScene().getRenderId();
  12173. return this._computedViewMatrix;
  12174. };
  12175. Camera.prototype.getProjectionMatrix = function (force) {
  12176. if (!force && this._isSynchronizedProjectionMatrix()) {
  12177. return this._projectionMatrix;
  12178. }
  12179. this._refreshFrustumPlanes = true;
  12180. var engine = this.getEngine();
  12181. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12182. if (this.minZ <= 0) {
  12183. this.minZ = 0.1;
  12184. }
  12185. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12186. return this._projectionMatrix;
  12187. }
  12188. var halfWidth = engine.getRenderWidth() / 2.0;
  12189. var halfHeight = engine.getRenderHeight() / 2.0;
  12190. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12191. return this._projectionMatrix;
  12192. };
  12193. Camera.prototype.getTranformationMatrix = function () {
  12194. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12195. return this._transformMatrix;
  12196. };
  12197. Camera.prototype.updateFrustumPlanes = function () {
  12198. if (!this._refreshFrustumPlanes) {
  12199. return;
  12200. }
  12201. this.getTranformationMatrix();
  12202. if (!this._frustumPlanes) {
  12203. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12204. }
  12205. else {
  12206. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12207. }
  12208. this._refreshFrustumPlanes = false;
  12209. };
  12210. Camera.prototype.isInFrustum = function (target) {
  12211. this.updateFrustumPlanes();
  12212. return target.isInFrustum(this._frustumPlanes);
  12213. };
  12214. Camera.prototype.isCompletelyInFrustum = function (target) {
  12215. this.updateFrustumPlanes();
  12216. return target.isCompletelyInFrustum(this._frustumPlanes);
  12217. };
  12218. Camera.prototype.dispose = function () {
  12219. // Animations
  12220. this.getScene().stopAnimation(this);
  12221. // Remove from scene
  12222. this.getScene().removeCamera(this);
  12223. while (this._rigCameras.length > 0) {
  12224. this._rigCameras.pop().dispose();
  12225. }
  12226. // Postprocesses
  12227. for (var i = 0; i < this._postProcesses.length; ++i) {
  12228. this._postProcesses[i].dispose(this);
  12229. }
  12230. _super.prototype.dispose.call(this);
  12231. };
  12232. // ---- Camera rigs section ----
  12233. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12234. while (this._rigCameras.length > 0) {
  12235. this._rigCameras.pop().dispose();
  12236. }
  12237. this.cameraRigMode = mode;
  12238. this._cameraRigParams = {};
  12239. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12240. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12241. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12242. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12243. // create the rig cameras, unless none
  12244. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12245. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12246. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12247. }
  12248. switch (this.cameraRigMode) {
  12249. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12250. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12251. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12252. break;
  12253. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12254. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12255. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12256. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12257. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12258. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12259. break;
  12260. case Camera.RIG_MODE_VR:
  12261. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12262. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12263. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12264. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12265. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12266. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12267. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12268. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12269. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12270. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12271. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12272. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12273. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12274. if (metrics.compensateDistortion) {
  12275. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12276. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12277. }
  12278. break;
  12279. }
  12280. this._cascadePostProcessesToRigCams();
  12281. this.
  12282. update();
  12283. };
  12284. Camera.prototype._getVRProjectionMatrix = function () {
  12285. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12286. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12287. return this._projectionMatrix;
  12288. };
  12289. Camera.prototype.setCameraRigParameter = function (name, value) {
  12290. if (!this._cameraRigParams) {
  12291. this._cameraRigParams = {};
  12292. }
  12293. this._cameraRigParams[name] = value;
  12294. //provisionnally:
  12295. if (name === "interaxialDistance") {
  12296. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12297. }
  12298. };
  12299. /**
  12300. * needs to be overridden by children so sub has required properties to be copied
  12301. */
  12302. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12303. return null;
  12304. };
  12305. /**
  12306. * May need to be overridden by children
  12307. */
  12308. Camera.prototype._updateRigCameras = function () {
  12309. for (var i = 0; i < this._rigCameras.length; i++) {
  12310. this._rigCameras[i].minZ = this.minZ;
  12311. this._rigCameras[i].maxZ = this.maxZ;
  12312. this._rigCameras[i].fov = this.fov;
  12313. }
  12314. // only update viewport when ANAGLYPH
  12315. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12316. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12317. }
  12318. };
  12319. Camera.prototype._setupInputs = function () {
  12320. };
  12321. Camera.prototype.serialize = function () {
  12322. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12323. // Type
  12324. serializationObject.type = this.getTypeName();
  12325. // Parent
  12326. if (this.parent) {
  12327. serializationObject.parentId = this.parent.id;
  12328. }
  12329. if (this.inputs) {
  12330. this.inputs.serialize(serializationObject);
  12331. }
  12332. // Animations
  12333. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12334. serializationObject.ranges = this.serializeAnimationRanges();
  12335. return serializationObject;
  12336. };
  12337. Camera.prototype.getTypeName = function () {
  12338. return "Camera";
  12339. };
  12340. Camera.prototype.clone = function (name) {
  12341. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12342. };
  12343. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12344. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12345. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12346. switch (type) {
  12347. case "ArcRotateCamera":
  12348. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12349. case "DeviceOrientationCamera":
  12350. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12351. case "FollowCamera":
  12352. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12353. case "ArcFollowCamera":
  12354. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12355. case "GamepadCamera":
  12356. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12357. case "TouchCamera":
  12358. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12359. case "VirtualJoysticksCamera":
  12360. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12361. case "WebVRFreeCamera":
  12362. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12363. case "VRDeviceOrientationFreeCamera":
  12364. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12365. case "AnaglyphArcRotateCamera":
  12366. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12367. case "AnaglyphFreeCamera":
  12368. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12369. case "AnaglyphGamepadCamera":
  12370. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12371. case "AnaglyphUniversalCamera":
  12372. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12373. case "StereoscopicArcRotateCamera":
  12374. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12375. case "StereoscopicFreeCamera":
  12376. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12377. case "StereoscopicGamepadCamera":
  12378. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12379. case "StereoscopicUniversalCamera":
  12380. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12381. case "FreeCamera":
  12382. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12383. default:
  12384. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12385. }
  12386. };
  12387. Camera.Parse = function (parsedCamera, scene) {
  12388. var type = parsedCamera.type;
  12389. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12390. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12391. // Parent
  12392. if (parsedCamera.parentId) {
  12393. camera._waitingParentId = parsedCamera.parentId;
  12394. }
  12395. //If camera has an input manager, let it parse inputs settings
  12396. if (camera.inputs) {
  12397. camera.inputs.parse(parsedCamera);
  12398. camera._setupInputs();
  12399. }
  12400. // Target
  12401. if (parsedCamera.target) {
  12402. if (camera.setTarget) {
  12403. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12404. }
  12405. }
  12406. // Apply 3d rig, when found
  12407. if (parsedCamera.cameraRigMode) {
  12408. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12409. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12410. }
  12411. // Animations
  12412. if (parsedCamera.animations) {
  12413. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12414. var parsedAnimation = parsedCamera.animations[animationIndex];
  12415. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12416. }
  12417. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12418. }
  12419. if (parsedCamera.autoAnimate) {
  12420. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12421. }
  12422. return camera;
  12423. };
  12424. // Statics
  12425. Camera._PERSPECTIVE_CAMERA = 0;
  12426. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12427. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12428. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12429. Camera._RIG_MODE_NONE = 0;
  12430. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12431. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12432. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12433. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12434. Camera._RIG_MODE_VR = 20;
  12435. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12436. __decorate([
  12437. BABYLON.serializeAsVector3()
  12438. ], Camera.prototype, "position", void 0);
  12439. __decorate([
  12440. BABYLON.serializeAsVector3()
  12441. ], Camera.prototype, "upVector", void 0);
  12442. __decorate([
  12443. BABYLON.serialize()
  12444. ], Camera.prototype, "orthoLeft", void 0);
  12445. __decorate([
  12446. BABYLON.serialize()
  12447. ], Camera.prototype, "orthoRight", void 0);
  12448. __decorate([
  12449. BABYLON.serialize()
  12450. ], Camera.prototype, "orthoBottom", void 0);
  12451. __decorate([
  12452. BABYLON.serialize()
  12453. ], Camera.prototype, "orthoTop", void 0);
  12454. __decorate([
  12455. BABYLON.serialize()
  12456. ], Camera.prototype, "fov", void 0);
  12457. __decorate([
  12458. BABYLON.serialize()
  12459. ], Camera.prototype, "minZ", void 0);
  12460. __decorate([
  12461. BABYLON.serialize()
  12462. ], Camera.prototype, "maxZ", void 0);
  12463. __decorate([
  12464. BABYLON.serialize()
  12465. ], Camera.prototype, "inertia", void 0);
  12466. __decorate([
  12467. BABYLON.serialize()
  12468. ], Camera.prototype, "mode", void 0);
  12469. __decorate([
  12470. BABYLON.serialize()
  12471. ], Camera.prototype, "layerMask", void 0);
  12472. __decorate([
  12473. BABYLON.serialize()
  12474. ], Camera.prototype, "fovMode", void 0);
  12475. __decorate([
  12476. BABYLON.serialize()
  12477. ], Camera.prototype, "cameraRigMode", void 0);
  12478. __decorate([
  12479. BABYLON.serialize()
  12480. ], Camera.prototype, "interaxialDistance", void 0);
  12481. __decorate([
  12482. BABYLON.serialize()
  12483. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12484. return Camera;
  12485. })(BABYLON.Node);
  12486. BABYLON.Camera = Camera;
  12487. })(BABYLON || (BABYLON = {}));
  12488. var BABYLON;
  12489. (function (BABYLON) {
  12490. BABYLON.CameraInputTypes = {};
  12491. var CameraInputsManager = (function () {
  12492. function CameraInputsManager(camera) {
  12493. this.attached = {};
  12494. this.camera = camera;
  12495. this.checkInputs = function () { };
  12496. }
  12497. CameraInputsManager.prototype.add = function (input) {
  12498. var type = input.getSimpleName();
  12499. if (this.attached[type]) {
  12500. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12501. return;
  12502. }
  12503. this.attached[type] = input;
  12504. input.camera = this.camera;
  12505. //for checkInputs, we are dynamically creating a function
  12506. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12507. if (input.checkInputs) {
  12508. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12509. }
  12510. if (this.attachedElement) {
  12511. input.attachControl(this.attachedElement);
  12512. }
  12513. };
  12514. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12515. for (var cam in this.attached) {
  12516. var input = this.attached[cam];
  12517. if (input === inputToRemove) {
  12518. input.detachControl(this.attachedElement);
  12519. delete this.attached[cam];
  12520. this.rebuildInputCheck();
  12521. }
  12522. }
  12523. };
  12524. CameraInputsManager.prototype.removeByType = function (inputType) {
  12525. for (var cam in this.attached) {
  12526. var input = this.attached[cam];
  12527. if (input.getTypeName() === inputType) {
  12528. input.detachControl(this.attachedElement);
  12529. delete this.attached[cam];
  12530. this.rebuildInputCheck();
  12531. }
  12532. }
  12533. };
  12534. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12535. var current = this.checkInputs;
  12536. return function () {
  12537. current();
  12538. fn();
  12539. };
  12540. };
  12541. CameraInputsManager.prototype.attachInput = function (input) {
  12542. input.attachControl(this.attachedElement, this.noPreventDefault);
  12543. };
  12544. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12545. if (this.attachedElement) {
  12546. return;
  12547. }
  12548. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12549. this.attachedElement = element;
  12550. this.noPreventDefault = noPreventDefault;
  12551. for (var cam in this.attached) {
  12552. var input = this.attached[cam];
  12553. this.attached[cam].attachControl(element, noPreventDefault);
  12554. }
  12555. };
  12556. CameraInputsManager.prototype.detachElement = function (element) {
  12557. if (this.attachedElement !== element) {
  12558. return;
  12559. }
  12560. for (var cam in this.attached) {
  12561. var input = this.attached[cam];
  12562. this.attached[cam].detachControl(element);
  12563. }
  12564. this.attachedElement = null;
  12565. };
  12566. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12567. this.checkInputs = function () { };
  12568. for (var cam in this.attached) {
  12569. var input = this.attached[cam];
  12570. if (input.checkInputs) {
  12571. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12572. }
  12573. }
  12574. };
  12575. CameraInputsManager.prototype.clear = function () {
  12576. if (this.attachedElement) {
  12577. this.detachElement(this.attachedElement);
  12578. }
  12579. this.attached = {};
  12580. this.attachedElement = null;
  12581. this.checkInputs = function () { };
  12582. };
  12583. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  12584. var inputs = {};
  12585. for (var cam in this.attached) {
  12586. var input = this.attached[cam];
  12587. var res = BABYLON.SerializationHelper.Serialize(input);
  12588. inputs[input.getTypeName()] = res;
  12589. }
  12590. serializedCamera.inputsmgr = inputs;
  12591. };
  12592. CameraInputsManager.prototype.parse = function (parsedCamera) {
  12593. var parsedInputs = parsedCamera.inputsmgr;
  12594. if (parsedInputs) {
  12595. this.clear();
  12596. for (var n in parsedInputs) {
  12597. var construct = BABYLON.CameraInputTypes[n];
  12598. if (construct) {
  12599. var parsedinput = parsedInputs[n];
  12600. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  12601. this.add(input);
  12602. }
  12603. }
  12604. }
  12605. else {
  12606. //2016-03-08 this part is for managing backward compatibility
  12607. for (var n in this.attached) {
  12608. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  12609. if (construct) {
  12610. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  12611. this.remove(this.attached[n]);
  12612. this.add(input);
  12613. }
  12614. }
  12615. }
  12616. };
  12617. return CameraInputsManager;
  12618. })();
  12619. BABYLON.CameraInputsManager = CameraInputsManager;
  12620. })(BABYLON || (BABYLON = {}));
  12621. var BABYLON;
  12622. (function (BABYLON) {
  12623. var FreeCameraMouseInput = (function () {
  12624. function FreeCameraMouseInput(touchEnabled) {
  12625. if (touchEnabled === void 0) { touchEnabled = true; }
  12626. this.touchEnabled = touchEnabled;
  12627. this.angularSensibility = 2000.0;
  12628. }
  12629. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  12630. var _this = this;
  12631. if (!this._pointerInput) {
  12632. var camera = this.camera;
  12633. var engine = this.camera.getEngine();
  12634. this._pointerInput = function (p, s) {
  12635. var evt = p.event;
  12636. if (!_this.touchEnabled && evt.pointerType === "touch") {
  12637. return;
  12638. }
  12639. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12640. try {
  12641. evt.srcElement.setPointerCapture(evt.pointerId);
  12642. }
  12643. catch (e) {
  12644. }
  12645. _this.previousPosition = {
  12646. x: evt.clientX,
  12647. y: evt.clientY
  12648. };
  12649. if (!noPreventDefault) {
  12650. evt.preventDefault();
  12651. element.focus();
  12652. }
  12653. }
  12654. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12655. try {
  12656. evt.srcElement.releasePointerCapture(evt.pointerId);
  12657. }
  12658. catch (e) {
  12659. }
  12660. _this.previousPosition = null;
  12661. if (!noPreventDefault) {
  12662. evt.preventDefault();
  12663. }
  12664. }
  12665. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12666. if (!_this.previousPosition && !engine.isPointerLock) {
  12667. return;
  12668. }
  12669. var offsetX;
  12670. var offsetY;
  12671. if (!engine.isPointerLock) {
  12672. offsetX = evt.clientX - _this.previousPosition.x;
  12673. offsetY = evt.clientY - _this.previousPosition.y;
  12674. }
  12675. else {
  12676. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12677. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12678. }
  12679. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  12680. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  12681. _this.previousPosition = {
  12682. x: evt.clientX,
  12683. y: evt.clientY
  12684. };
  12685. if (!noPreventDefault) {
  12686. evt.preventDefault();
  12687. }
  12688. }
  12689. };
  12690. }
  12691. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12692. };
  12693. FreeCameraMouseInput.prototype.detachControl = function (element) {
  12694. if (this._observer && element) {
  12695. this.camera.getScene().onPointerObservable.remove(this._observer);
  12696. this._observer = null;
  12697. this.previousPosition = null;
  12698. }
  12699. };
  12700. FreeCameraMouseInput.prototype.getTypeName = function () {
  12701. return "FreeCameraMouseInput";
  12702. };
  12703. FreeCameraMouseInput.prototype.getSimpleName = function () {
  12704. return "mouse";
  12705. };
  12706. __decorate([
  12707. BABYLON.serialize()
  12708. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  12709. return FreeCameraMouseInput;
  12710. })();
  12711. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  12712. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  12713. })(BABYLON || (BABYLON = {}));
  12714. var BABYLON;
  12715. (function (BABYLON) {
  12716. var FreeCameraKeyboardMoveInput = (function () {
  12717. function FreeCameraKeyboardMoveInput() {
  12718. this._keys = [];
  12719. this.keysUp = [38];
  12720. this.keysDown = [40];
  12721. this.keysLeft = [37];
  12722. this.keysRight = [39];
  12723. }
  12724. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12725. var _this = this;
  12726. if (!this._onKeyDown) {
  12727. element.tabIndex = 1;
  12728. this._onKeyDown = function (evt) {
  12729. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12730. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12731. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12732. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12733. var index = _this._keys.indexOf(evt.keyCode);
  12734. if (index === -1) {
  12735. _this._keys.push(evt.keyCode);
  12736. }
  12737. if (!noPreventDefault) {
  12738. evt.preventDefault();
  12739. }
  12740. }
  12741. };
  12742. this._onKeyUp = function (evt) {
  12743. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12744. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12745. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12746. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12747. var index = _this._keys.indexOf(evt.keyCode);
  12748. if (index >= 0) {
  12749. _this._keys.splice(index, 1);
  12750. }
  12751. if (!noPreventDefault) {
  12752. evt.preventDefault();
  12753. }
  12754. }
  12755. };
  12756. element.addEventListener("keydown", this._onKeyDown, false);
  12757. element.addEventListener("keyup", this._onKeyUp, false);
  12758. BABYLON.Tools.RegisterTopRootEvents([
  12759. { name: "blur", handler: this._onLostFocus }
  12760. ]);
  12761. }
  12762. };
  12763. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12764. if (this._onKeyDown) {
  12765. element.removeEventListener("keydown", this._onKeyDown);
  12766. element.removeEventListener("keyup", this._onKeyUp);
  12767. BABYLON.Tools.UnregisterTopRootEvents([
  12768. { name: "blur", handler: this._onLostFocus }
  12769. ]);
  12770. this._keys = [];
  12771. this._onKeyDown = null;
  12772. this._onKeyUp = null;
  12773. }
  12774. };
  12775. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12776. if (this._onKeyDown) {
  12777. var camera = this.camera;
  12778. // Keyboard
  12779. for (var index = 0; index < this._keys.length; index++) {
  12780. var keyCode = this._keys[index];
  12781. var speed = camera._computeLocalCameraSpeed();
  12782. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12783. camera._localDirection.copyFromFloats(-speed, 0, 0);
  12784. }
  12785. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12786. camera._localDirection.copyFromFloats(0, 0, speed);
  12787. }
  12788. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12789. camera._localDirection.copyFromFloats(speed, 0, 0);
  12790. }
  12791. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12792. camera._localDirection.copyFromFloats(0, 0, -speed);
  12793. }
  12794. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  12795. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  12796. camera.cameraDirection.addInPlace(camera._transformedDirection);
  12797. }
  12798. }
  12799. };
  12800. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12801. return "FreeCameraKeyboardMoveInput";
  12802. };
  12803. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  12804. this._keys = [];
  12805. };
  12806. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12807. return "keyboard";
  12808. };
  12809. __decorate([
  12810. BABYLON.serialize()
  12811. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12812. __decorate([
  12813. BABYLON.serialize()
  12814. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12815. __decorate([
  12816. BABYLON.serialize()
  12817. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12818. __decorate([
  12819. BABYLON.serialize()
  12820. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12821. return FreeCameraKeyboardMoveInput;
  12822. })();
  12823. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  12824. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  12825. })(BABYLON || (BABYLON = {}));
  12826. var BABYLON;
  12827. (function (BABYLON) {
  12828. var FreeCameraTouchInput = (function () {
  12829. function FreeCameraTouchInput() {
  12830. this._offsetX = null;
  12831. this._offsetY = null;
  12832. this._pointerCount = 0;
  12833. this._pointerPressed = [];
  12834. this.touchAngularSensibility = 200000.0;
  12835. this.touchMoveSensibility = 250.0;
  12836. }
  12837. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  12838. var _this = this;
  12839. var previousPosition;
  12840. if (this._pointerInput === undefined) {
  12841. this._onLostFocus = function (evt) {
  12842. _this._offsetX = null;
  12843. _this._offsetY = null;
  12844. };
  12845. this._pointerInput = function (p, s) {
  12846. var evt = p.event;
  12847. if (evt.pointerType === "mouse") {
  12848. return;
  12849. }
  12850. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12851. if (!noPreventDefault) {
  12852. evt.preventDefault();
  12853. }
  12854. _this._pointerPressed.push(evt.pointerId);
  12855. if (_this._pointerPressed.length !== 1) {
  12856. return;
  12857. }
  12858. previousPosition = {
  12859. x: evt.clientX,
  12860. y: evt.clientY
  12861. };
  12862. }
  12863. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12864. if (!noPreventDefault) {
  12865. evt.preventDefault();
  12866. }
  12867. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12868. if (index === -1) {
  12869. return;
  12870. }
  12871. _this._pointerPressed.splice(index, 1);
  12872. if (index != 0) {
  12873. return;
  12874. }
  12875. previousPosition = null;
  12876. _this._offsetX = null;
  12877. _this._offsetY = null;
  12878. }
  12879. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12880. if (!noPreventDefault) {
  12881. evt.preventDefault();
  12882. }
  12883. if (!previousPosition) {
  12884. return;
  12885. }
  12886. var index = _this._pointerPressed.indexOf(evt.pointerId);
  12887. if (index != 0) {
  12888. return;
  12889. }
  12890. _this._offsetX = evt.clientX - previousPosition.x;
  12891. _this._offsetY = -(evt.clientY - previousPosition.y);
  12892. }
  12893. };
  12894. }
  12895. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12896. element.addEventListener("blur", this._onLostFocus);
  12897. };
  12898. FreeCameraTouchInput.prototype.detachControl = function (element) {
  12899. if (this._pointerInput && element) {
  12900. this.camera.getScene().onPointerObservable.remove(this._observer);
  12901. this._observer = null;
  12902. element.removeEventListener("blur", this._onLostFocus);
  12903. this._onLostFocus = null;
  12904. this._pointerPressed = [];
  12905. this._offsetX = null;
  12906. this._offsetY = null;
  12907. this._pointerCount = 0;
  12908. }
  12909. };
  12910. FreeCameraTouchInput.prototype.checkInputs = function () {
  12911. if (this._offsetX) {
  12912. var camera = this.camera;
  12913. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  12914. if (this._pointerPressed.length > 1) {
  12915. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  12916. }
  12917. else {
  12918. var speed = camera._computeLocalCameraSpeed();
  12919. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  12920. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12921. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12922. }
  12923. }
  12924. };
  12925. FreeCameraTouchInput.prototype.getTypeName = function () {
  12926. return "FreeCameraTouchInput";
  12927. };
  12928. FreeCameraTouchInput.prototype.getSimpleName = function () {
  12929. return "touch";
  12930. };
  12931. __decorate([
  12932. BABYLON.serialize()
  12933. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  12934. __decorate([
  12935. BABYLON.serialize()
  12936. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  12937. return FreeCameraTouchInput;
  12938. })();
  12939. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  12940. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  12941. })(BABYLON || (BABYLON = {}));
  12942. var BABYLON;
  12943. (function (BABYLON) {
  12944. var FreeCameraDeviceOrientationInput = (function () {
  12945. function FreeCameraDeviceOrientationInput() {
  12946. var _this = this;
  12947. this._screenOrientationAngle = 0;
  12948. this._screenQuaternion = new BABYLON.Quaternion();
  12949. this._alpha = 0;
  12950. this._beta = 0;
  12951. this._gamma = 0;
  12952. this._orientationChanged = function () {
  12953. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  12954. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  12955. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  12956. };
  12957. this._deviceOrientation = function (evt) {
  12958. _this._alpha = evt.alpha;
  12959. _this._beta = evt.beta;
  12960. _this._gamma = evt.gamma;
  12961. };
  12962. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  12963. this._orientationChanged();
  12964. }
  12965. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  12966. get: function () {
  12967. return this._camera;
  12968. },
  12969. set: function (camera) {
  12970. this._camera = camera;
  12971. if (!this._camera.rotationQuaternion)
  12972. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  12973. },
  12974. enumerable: true,
  12975. configurable: true
  12976. });
  12977. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12978. window.addEventListener("orientationchange", this._orientationChanged);
  12979. window.addEventListener("deviceorientation", this._deviceOrientation);
  12980. };
  12981. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12982. window.removeEventListener("orientationchange", this._orientationChanged);
  12983. window.removeEventListener("deviceorientation", this._deviceOrientation);
  12984. };
  12985. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12986. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  12987. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  12988. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  12989. //Mirror on XY Plane
  12990. this._camera.rotationQuaternion.z *= -1;
  12991. this._camera.rotationQuaternion.w *= -1;
  12992. };
  12993. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12994. return "FreeCameraDeviceOrientationInput";
  12995. };
  12996. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12997. return "deviceOrientation";
  12998. };
  12999. return FreeCameraDeviceOrientationInput;
  13000. })();
  13001. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13002. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13003. })(BABYLON || (BABYLON = {}));
  13004. var BABYLON;
  13005. (function (BABYLON) {
  13006. var FreeCameraVRDeviceOrientationInput = (function () {
  13007. function FreeCameraVRDeviceOrientationInput() {
  13008. this.alphaCorrection = 1;
  13009. this.betaCorrection = 1;
  13010. this.gammaCorrection = 1;
  13011. this._alpha = 0;
  13012. this._beta = 0;
  13013. this._gamma = 0;
  13014. this._dirty = false;
  13015. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13016. }
  13017. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13018. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13019. };
  13020. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13021. var camera = this.camera;
  13022. this._alpha = evt.alpha;
  13023. this._beta = evt.beta;
  13024. this._gamma = evt.gamma;
  13025. this._dirty = true;
  13026. };
  13027. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13028. if (this._dirty) {
  13029. this._dirty = false;
  13030. var rotationX = this._gamma;
  13031. if (rotationX < 0) {
  13032. rotationX = 90 + rotationX;
  13033. }
  13034. else {
  13035. // Incline it in the correct angle.
  13036. rotationX = 270 - rotationX;
  13037. }
  13038. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  13039. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  13040. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  13041. }
  13042. };
  13043. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13044. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13045. };
  13046. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13047. return "FreeCameraVRDeviceOrientationInput";
  13048. };
  13049. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13050. return "VRDeviceOrientation";
  13051. };
  13052. return FreeCameraVRDeviceOrientationInput;
  13053. })();
  13054. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  13055. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  13056. })(BABYLON || (BABYLON = {}));
  13057. var BABYLON;
  13058. (function (BABYLON) {
  13059. var FreeCameraGamepadInput = (function () {
  13060. function FreeCameraGamepadInput() {
  13061. this.gamepadAngularSensibility = 200;
  13062. this.gamepadMoveSensibility = 40;
  13063. }
  13064. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13065. var _this = this;
  13066. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13067. };
  13068. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13069. if (this._gamepads) {
  13070. this._gamepads.dispose();
  13071. }
  13072. this.gamepad = null;
  13073. };
  13074. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13075. if (this.gamepad) {
  13076. var camera = this.camera;
  13077. var LSValues = this.gamepad.leftStick;
  13078. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13079. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13080. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13081. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13082. var RSValues = this.gamepad.rightStick;
  13083. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13084. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13085. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13086. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13087. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13088. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13089. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13090. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13091. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13092. }
  13093. };
  13094. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13095. // Only the first gamepad can control the camera
  13096. if (gamepad.index === 0) {
  13097. this.gamepad = gamepad;
  13098. }
  13099. };
  13100. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13101. return "FreeCameraGamepadInput";
  13102. };
  13103. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13104. return "gamepad";
  13105. };
  13106. __decorate([
  13107. BABYLON.serialize()
  13108. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13109. __decorate([
  13110. BABYLON.serialize()
  13111. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13112. return FreeCameraGamepadInput;
  13113. })();
  13114. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13115. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13116. })(BABYLON || (BABYLON = {}));
  13117. var BABYLON;
  13118. (function (BABYLON) {
  13119. var ArcRotateCameraKeyboardMoveInput = (function () {
  13120. function ArcRotateCameraKeyboardMoveInput() {
  13121. this._keys = [];
  13122. this.keysUp = [38];
  13123. this.keysDown = [40];
  13124. this.keysLeft = [37];
  13125. this.keysRight = [39];
  13126. }
  13127. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13128. var _this = this;
  13129. element.tabIndex = 1;
  13130. this._onKeyDown = function (evt) {
  13131. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13132. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13133. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13134. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13135. var index = _this._keys.indexOf(evt.keyCode);
  13136. if (index === -1) {
  13137. _this._keys.push(evt.keyCode);
  13138. }
  13139. if (evt.preventDefault) {
  13140. if (!noPreventDefault) {
  13141. evt.preventDefault();
  13142. }
  13143. }
  13144. }
  13145. };
  13146. this._onKeyUp = function (evt) {
  13147. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13148. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13149. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13150. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13151. var index = _this._keys.indexOf(evt.keyCode);
  13152. if (index >= 0) {
  13153. _this._keys.splice(index, 1);
  13154. }
  13155. if (evt.preventDefault) {
  13156. if (!noPreventDefault) {
  13157. evt.preventDefault();
  13158. }
  13159. }
  13160. }
  13161. };
  13162. this._onLostFocus = function () {
  13163. _this._keys = [];
  13164. };
  13165. element.addEventListener("keydown", this._onKeyDown, false);
  13166. element.addEventListener("keyup", this._onKeyUp, false);
  13167. BABYLON.Tools.RegisterTopRootEvents([
  13168. { name: "blur", handler: this._onLostFocus }
  13169. ]);
  13170. };
  13171. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13172. if (element) {
  13173. element.removeEventListener("keydown", this._onKeyDown);
  13174. element.removeEventListener("keyup", this._onKeyUp);
  13175. }
  13176. BABYLON.Tools.UnregisterTopRootEvents([
  13177. { name: "blur", handler: this._onLostFocus }
  13178. ]);
  13179. this._keys = [];
  13180. this._onKeyDown = null;
  13181. this._onKeyUp = null;
  13182. this._onLostFocus = null;
  13183. };
  13184. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13185. if (this._onKeyDown) {
  13186. var camera = this.camera;
  13187. for (var index = 0; index < this._keys.length; index++) {
  13188. var keyCode = this._keys[index];
  13189. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13190. camera.inertialAlphaOffset -= 0.01;
  13191. }
  13192. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13193. camera.inertialBetaOffset -= 0.01;
  13194. }
  13195. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13196. camera.inertialAlphaOffset += 0.01;
  13197. }
  13198. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13199. camera.inertialBetaOffset += 0.01;
  13200. }
  13201. }
  13202. }
  13203. };
  13204. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13205. return "ArcRotateCameraKeyboardMoveInput";
  13206. };
  13207. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13208. return "keyboard";
  13209. };
  13210. __decorate([
  13211. BABYLON.serialize()
  13212. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13213. __decorate([
  13214. BABYLON.serialize()
  13215. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13216. __decorate([
  13217. BABYLON.serialize()
  13218. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13219. __decorate([
  13220. BABYLON.serialize()
  13221. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13222. return ArcRotateCameraKeyboardMoveInput;
  13223. })();
  13224. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13225. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13226. })(BABYLON || (BABYLON = {}));
  13227. var BABYLON;
  13228. (function (BABYLON) {
  13229. var ArcRotateCameraMouseWheelInput = (function () {
  13230. function ArcRotateCameraMouseWheelInput() {
  13231. this.wheelPrecision = 3.0;
  13232. }
  13233. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13234. var _this = this;
  13235. this._wheel = function (p, s) {
  13236. //sanity check - this should be a PointerWheel event.
  13237. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13238. return;
  13239. var event = p.event;
  13240. var delta = 0;
  13241. if (event.wheelDelta) {
  13242. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13243. }
  13244. else if (event.detail) {
  13245. delta = -event.detail / _this.wheelPrecision;
  13246. }
  13247. if (delta)
  13248. _this.camera.inertialRadiusOffset += delta;
  13249. if (event.preventDefault) {
  13250. if (!noPreventDefault) {
  13251. event.preventDefault();
  13252. }
  13253. }
  13254. };
  13255. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13256. };
  13257. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13258. if (this._observer && element) {
  13259. this.camera.getScene().onPointerObservable.remove(this._observer);
  13260. this._observer = null;
  13261. this._wheel = null;
  13262. }
  13263. };
  13264. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13265. return "ArcRotateCameraMouseWheelInput";
  13266. };
  13267. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13268. return "mousewheel";
  13269. };
  13270. __decorate([
  13271. BABYLON.serialize()
  13272. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13273. return ArcRotateCameraMouseWheelInput;
  13274. })();
  13275. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13276. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13277. })(BABYLON || (BABYLON = {}));
  13278. var BABYLON;
  13279. (function (BABYLON) {
  13280. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13281. var ArcRotateCameraPointersInput = (function () {
  13282. function ArcRotateCameraPointersInput() {
  13283. this.angularSensibilityX = 1000.0;
  13284. this.angularSensibilityY = 1000.0;
  13285. this.pinchPrecision = 6.0;
  13286. this.panningSensibility = 50.0;
  13287. this._isPanClick = false;
  13288. this._isCtrlPushed = false;
  13289. this.pinchInwards = true;
  13290. }
  13291. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13292. var _this = this;
  13293. var engine = this.camera.getEngine();
  13294. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13295. var pointA, pointB;
  13296. var previousPinchDistance = 0;
  13297. this._pointerInput = function (p, s) {
  13298. var evt = p.event;
  13299. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13300. try {
  13301. evt.srcElement.setPointerCapture(evt.pointerId);
  13302. }
  13303. catch (e) {
  13304. }
  13305. // Manage panning with pan button click
  13306. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13307. // manage pointers
  13308. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13309. if (pointA === undefined) {
  13310. pointA = cacheSoloPointer;
  13311. }
  13312. else if (pointB === undefined) {
  13313. pointB = cacheSoloPointer;
  13314. }
  13315. if (!noPreventDefault) {
  13316. evt.preventDefault();
  13317. element.focus();
  13318. }
  13319. }
  13320. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13321. try {
  13322. evt.srcElement.releasePointerCapture(evt.pointerId);
  13323. }
  13324. catch (e) {
  13325. }
  13326. cacheSoloPointer = null;
  13327. previousPinchDistance = 0;
  13328. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13329. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13330. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13331. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13332. pointA = pointB = undefined;
  13333. if (!noPreventDefault) {
  13334. evt.preventDefault();
  13335. }
  13336. }
  13337. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13338. if (!noPreventDefault) {
  13339. evt.preventDefault();
  13340. }
  13341. // One button down
  13342. if (pointA && pointB === undefined) {
  13343. if (_this.panningSensibility !== 0 &&
  13344. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  13345. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13346. _this.camera
  13347. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13348. _this.camera
  13349. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13350. }
  13351. else {
  13352. var offsetX = evt.clientX - cacheSoloPointer.x;
  13353. var offsetY = evt.clientY - cacheSoloPointer.y;
  13354. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13355. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13356. }
  13357. console.log(_this.camera.name);
  13358. console.log(_this.camera.inertialAlphaOffset);
  13359. cacheSoloPointer.x = evt.clientX;
  13360. cacheSoloPointer.y = evt.clientY;
  13361. }
  13362. else if (pointA && pointB) {
  13363. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13364. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13365. ed.x = evt.clientX;
  13366. ed.y = evt.clientY;
  13367. var direction = _this.pinchInwards ? 1 : -1;
  13368. var distX = pointA.x - pointB.x;
  13369. var distY = pointA.y - pointB.y;
  13370. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13371. if (previousPinchDistance === 0) {
  13372. previousPinchDistance = pinchSquaredDistance;
  13373. return;
  13374. }
  13375. if (pinchSquaredDistance !== previousPinchDistance) {
  13376. _this.camera
  13377. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13378. (_this.pinchPrecision *
  13379. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13380. direction);
  13381. previousPinchDistance = pinchSquaredDistance;
  13382. }
  13383. }
  13384. }
  13385. };
  13386. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13387. this._onContextMenu = function (evt) {
  13388. evt.preventDefault();
  13389. };
  13390. if (!this.camera._useCtrlForPanning) {
  13391. element.addEventListener("contextmenu", this._onContextMenu, false);
  13392. }
  13393. this._onLostFocus = function () {
  13394. //this._keys = [];
  13395. pointA = pointB = undefined;
  13396. previousPinchDistance = 0;
  13397. cacheSoloPointer = null;
  13398. };
  13399. this._onKeyDown = function (evt) {
  13400. _this._isCtrlPushed = evt.ctrlKey;
  13401. };
  13402. this._onKeyUp = function (evt) {
  13403. _this._isCtrlPushed = evt.ctrlKey;
  13404. };
  13405. this._onMouseMove = function (evt) {
  13406. if (!engine.isPointerLock) {
  13407. return;
  13408. }
  13409. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13410. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13411. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13412. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13413. if (!noPreventDefault) {
  13414. evt.preventDefault();
  13415. }
  13416. };
  13417. this._onGestureStart = function (e) {
  13418. if (window.MSGesture === undefined) {
  13419. return;
  13420. }
  13421. if (!_this._MSGestureHandler) {
  13422. _this._MSGestureHandler = new MSGesture();
  13423. _this._MSGestureHandler.target = element;
  13424. }
  13425. _this._MSGestureHandler.addPointer(e.pointerId);
  13426. };
  13427. this._onGesture = function (e) {
  13428. _this.camera.radius *= e.scale;
  13429. if (e.preventDefault) {
  13430. if (!noPreventDefault) {
  13431. e.stopPropagation();
  13432. e.preventDefault();
  13433. }
  13434. }
  13435. };
  13436. element.addEventListener("mousemove", this._onMouseMove, false);
  13437. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13438. element.addEventListener("MSGestureChange", this._onGesture, false);
  13439. element.addEventListener("keydown", this._onKeyDown, false);
  13440. element.addEventListener("keyup", this._onKeyUp, false);
  13441. BABYLON.Tools.RegisterTopRootEvents([
  13442. { name: "blur", handler: this._onLostFocus }
  13443. ]);
  13444. };
  13445. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13446. if (element && this._observer) {
  13447. this.camera.getScene().onPointerObservable.remove(this._observer);
  13448. this._observer = null;
  13449. element.removeEventListener("contextmenu", this._onContextMenu);
  13450. element.removeEventListener("mousemove", this._onMouseMove);
  13451. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13452. element.removeEventListener("MSGestureChange", this._onGesture);
  13453. element.removeEventListener("keydown", this._onKeyDown);
  13454. element.removeEventListener("keyup", this._onKeyUp);
  13455. this._isPanClick = false;
  13456. this._isCtrlPushed = false;
  13457. this.pinchInwards = true;
  13458. this._onKeyDown = null;
  13459. this._onKeyUp = null;
  13460. this._onMouseMove = null;
  13461. this._onGestureStart = null;
  13462. this._onGesture = null;
  13463. this._MSGestureHandler = null;
  13464. this._onLostFocus = null;
  13465. this._onContextMenu = null;
  13466. }
  13467. BABYLON.Tools.UnregisterTopRootEvents([
  13468. { name: "blur", handler: this._onLostFocus }
  13469. ]);
  13470. };
  13471. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13472. return "ArcRotateCameraPointersInput";
  13473. };
  13474. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13475. return "pointers";
  13476. };
  13477. __decorate([
  13478. BABYLON.serialize()
  13479. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13480. __decorate([
  13481. BABYLON.serialize()
  13482. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13483. __decorate([
  13484. BABYLON.serialize()
  13485. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13486. __decorate([
  13487. BABYLON.serialize()
  13488. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13489. return ArcRotateCameraPointersInput;
  13490. })();
  13491. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13492. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13493. })(BABYLON || (BABYLON = {}));
  13494. var BABYLON;
  13495. (function (BABYLON) {
  13496. var ArcRotateCameraGamepadInput = (function () {
  13497. function ArcRotateCameraGamepadInput() {
  13498. this.gamepadRotationSensibility = 80;
  13499. this.gamepadMoveSensibility = 40;
  13500. }
  13501. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13502. var _this = this;
  13503. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13504. };
  13505. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13506. if (this._gamepads) {
  13507. this._gamepads.dispose();
  13508. }
  13509. this.gamepad = null;
  13510. };
  13511. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13512. if (this.gamepad) {
  13513. var camera = this.camera;
  13514. var RSValues = this.gamepad.rightStick;
  13515. if (RSValues.x != 0) {
  13516. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13517. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13518. camera.inertialAlphaOffset += normalizedRX;
  13519. }
  13520. }
  13521. if (RSValues.y != 0) {
  13522. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13523. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13524. camera.inertialBetaOffset += normalizedRY;
  13525. }
  13526. }
  13527. var LSValues = this.gamepad.leftStick;
  13528. if (LSValues.y != 0) {
  13529. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13530. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13531. this.camera.inertialRadiusOffset -= normalizedLY;
  13532. }
  13533. }
  13534. }
  13535. };
  13536. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13537. // Only the first gamepad can control the camera
  13538. if (gamepad.index === 0) {
  13539. this.gamepad = gamepad;
  13540. }
  13541. };
  13542. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13543. return "ArcRotateCameraGamepadInput";
  13544. };
  13545. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13546. return "gamepad";
  13547. };
  13548. __decorate([
  13549. BABYLON.serialize()
  13550. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13551. __decorate([
  13552. BABYLON.serialize()
  13553. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13554. return ArcRotateCameraGamepadInput;
  13555. })();
  13556. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13557. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13558. })(BABYLON || (BABYLON = {}));
  13559. var BABYLON;
  13560. (function (BABYLON) {
  13561. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13562. function ArcRotateCameraVRDeviceOrientationInput() {
  13563. this.alphaCorrection = 1;
  13564. this.betaCorrection = 1;
  13565. this.gammaCorrection = 1;
  13566. this._alpha = 0;
  13567. this._beta = 0;
  13568. this._gamma = 0;
  13569. this._dirty = false;
  13570. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13571. }
  13572. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13573. this.camera.attachControl(element, noPreventDefault);
  13574. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13575. };
  13576. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13577. var camera = this.camera;
  13578. this._alpha = +evt.alpha | 0;
  13579. this._beta = +evt.beta | 0;
  13580. this._gamma = +evt.gamma | 0;
  13581. this._dirty = true;
  13582. };
  13583. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13584. if (this._dirty) {
  13585. this._dirty = false;
  13586. if (this._gamma < 0) {
  13587. this._gamma = 180 + this._gamma;
  13588. }
  13589. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13590. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13591. }
  13592. };
  13593. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13594. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13595. };
  13596. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13597. return "ArcRotateCameraVRDeviceOrientationInput";
  13598. };
  13599. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13600. return "VRDeviceOrientation";
  13601. };
  13602. return ArcRotateCameraVRDeviceOrientationInput;
  13603. })();
  13604. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13605. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13606. })(BABYLON || (BABYLON = {}));
  13607. var BABYLON;
  13608. (function (BABYLON) {
  13609. var TargetCamera = (function (_super) {
  13610. __extends(TargetCamera, _super);
  13611. function TargetCamera(name, position, scene) {
  13612. _super.call(this, name, position, scene);
  13613. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13614. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13615. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13616. this.speed = 2.0;
  13617. this.noRotationConstraint = false;
  13618. this.lockedTarget = null;
  13619. this._currentTarget = BABYLON.Vector3.Zero();
  13620. this._viewMatrix = BABYLON.Matrix.Zero();
  13621. this._camMatrix = BABYLON.Matrix.Zero();
  13622. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13623. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13624. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13625. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13626. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13627. this._lookAtTemp = BABYLON.Matrix.Zero();
  13628. this._tempMatrix = BABYLON.Matrix.Zero();
  13629. }
  13630. TargetCamera.prototype.getFrontPosition = function (distance) {
  13631. var direction = this.getTarget().subtract(this.position);
  13632. direction.normalize();
  13633. direction.scaleInPlace(distance);
  13634. return this.globalPosition.add(direction);
  13635. };
  13636. TargetCamera.prototype._getLockedTargetPosition = function () {
  13637. if (!this.lockedTarget) {
  13638. return null;
  13639. }
  13640. return this.lockedTarget.position || this.lockedTarget;
  13641. };
  13642. // Cache
  13643. TargetCamera.prototype._initCache = function () {
  13644. _super.prototype._initCache.call(this);
  13645. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13646. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13647. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13648. };
  13649. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  13650. if (!ignoreParentClass) {
  13651. _super.prototype._updateCache.call(this);
  13652. }
  13653. var lockedTargetPosition = this._getLockedTargetPosition();
  13654. if (!lockedTargetPosition) {
  13655. this._cache.lockedTarget = null;
  13656. }
  13657. else {
  13658. if (!this._cache.lockedTarget) {
  13659. this._cache.lockedTarget = lockedTargetPosition.clone();
  13660. }
  13661. else {
  13662. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  13663. }
  13664. }
  13665. this._cache.rotation.copyFrom(this.rotation);
  13666. if (this.rotationQuaternion)
  13667. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13668. };
  13669. // Synchronized
  13670. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  13671. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  13672. return false;
  13673. }
  13674. var lockedTargetPosition = this._getLockedTargetPosition();
  13675. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  13676. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  13677. };
  13678. // Methods
  13679. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  13680. var engine = this.getEngine();
  13681. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  13682. };
  13683. // Target
  13684. TargetCamera.prototype.setTarget = function (target) {
  13685. this.upVector.normalize();
  13686. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  13687. this._camMatrix.invert();
  13688. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  13689. var vDir = target.subtract(this.position);
  13690. if (vDir.x >= 0.0) {
  13691. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  13692. }
  13693. else {
  13694. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  13695. }
  13696. this.rotation.z = 0;
  13697. if (isNaN(this.rotation.x)) {
  13698. this.rotation.x = 0;
  13699. }
  13700. if (isNaN(this.rotation.y)) {
  13701. this.rotation.y = 0;
  13702. }
  13703. if (isNaN(this.rotation.z)) {
  13704. this.rotation.z = 0;
  13705. }
  13706. if (this.rotationQuaternion) {
  13707. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  13708. }
  13709. };
  13710. TargetCamera.prototype.getTarget = function () {
  13711. return this._currentTarget;
  13712. };
  13713. TargetCamera.prototype._decideIfNeedsToMove = function () {
  13714. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13715. };
  13716. TargetCamera.prototype._updatePosition = function () {
  13717. this.position.addInPlace(this.cameraDirection);
  13718. };
  13719. TargetCamera.prototype._checkInputs = function () {
  13720. var needToMove = this._decideIfNeedsToMove();
  13721. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  13722. // Move
  13723. if (needToMove) {
  13724. this._updatePosition();
  13725. }
  13726. // Rotate
  13727. if (needToRotate) {
  13728. this.rotation.x += this.cameraRotation.x;
  13729. this.rotation.y += this.cameraRotation.y;
  13730. if (!this.noRotationConstraint) {
  13731. var limit = (Math.PI / 2) * 0.95;
  13732. if (this.rotation.x > limit)
  13733. this.rotation.x = limit;
  13734. if (this.rotation.x < -limit)
  13735. this.rotation.x = -limit;
  13736. }
  13737. }
  13738. // Inertia
  13739. if (needToMove) {
  13740. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  13741. this.cameraDirection.x = 0;
  13742. }
  13743. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  13744. this.cameraDirection.y = 0;
  13745. }
  13746. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  13747. this.cameraDirection.z = 0;
  13748. }
  13749. this.cameraDirection.scaleInPlace(this.inertia);
  13750. }
  13751. if (needToRotate) {
  13752. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  13753. this.cameraRotation.x = 0;
  13754. }
  13755. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  13756. this.cameraRotation.y = 0;
  13757. }
  13758. this.cameraRotation.scaleInPlace(this.inertia);
  13759. }
  13760. _super.prototype._checkInputs.call(this);
  13761. };
  13762. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  13763. if (this.rotationQuaternion) {
  13764. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  13765. //update the up vector!
  13766. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  13767. }
  13768. else {
  13769. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  13770. }
  13771. };
  13772. TargetCamera.prototype._getViewMatrix = function () {
  13773. if (!this.lockedTarget) {
  13774. // Compute
  13775. this._updateCameraRotationMatrix();
  13776. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  13777. // Computing target and final matrix
  13778. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  13779. }
  13780. else {
  13781. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  13782. }
  13783. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  13784. return this._viewMatrix;
  13785. };
  13786. /**
  13787. * @override
  13788. * Override Camera.createRigCamera
  13789. */
  13790. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13791. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  13792. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  13793. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  13794. if (!this.rotationQuaternion) {
  13795. this.rotationQuaternion = new BABYLON.Quaternion();
  13796. }
  13797. rigCamera._cameraRigParams = {};
  13798. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  13799. }
  13800. return rigCamera;
  13801. }
  13802. return null;
  13803. };
  13804. /**
  13805. * @override
  13806. * Override Camera._updateRigCameras
  13807. */
  13808. TargetCamera.prototype._updateRigCameras = function () {
  13809. var camLeft = this._rigCameras[0];
  13810. var camRight = this._rigCameras[1];
  13811. switch (this.cameraRigMode) {
  13812. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13813. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13814. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13815. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13816. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  13817. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  13818. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  13819. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  13820. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  13821. camLeft.setTarget(this.getTarget());
  13822. camRight.setTarget(this.getTarget());
  13823. break;
  13824. case BABYLON.Camera.RIG_MODE_VR:
  13825. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13826. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13827. camLeft.position.copyFrom(this.position);
  13828. camRight.position.copyFrom(this.position);
  13829. break;
  13830. }
  13831. _super.prototype._updateRigCameras.call(this);
  13832. };
  13833. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  13834. if (!this._rigCamTransformMatrix) {
  13835. this._rigCamTransformMatrix = new BABYLON.Matrix();
  13836. }
  13837. var target = this.getTarget();
  13838. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  13839. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  13840. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  13841. };
  13842. TargetCamera.prototype.getTypeName = function () {
  13843. return "TargetCamera";
  13844. };
  13845. __decorate([
  13846. BABYLON.serializeAsVector3()
  13847. ], TargetCamera.prototype, "rotation", void 0);
  13848. __decorate([
  13849. BABYLON.serialize()
  13850. ], TargetCamera.prototype, "speed", void 0);
  13851. __decorate([
  13852. BABYLON.serializeAsMeshReference("lockedTargetId")
  13853. ], TargetCamera.prototype, "lockedTarget", void 0);
  13854. return TargetCamera;
  13855. })(BABYLON.Camera);
  13856. BABYLON.TargetCamera = TargetCamera;
  13857. })(BABYLON || (BABYLON = {}));
  13858. var BABYLON;
  13859. (function (BABYLON) {
  13860. var FreeCamera = (function (_super) {
  13861. __extends(FreeCamera, _super);
  13862. function FreeCamera(name, position, scene) {
  13863. var _this = this;
  13864. _super.call(this, name, position, scene);
  13865. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13866. this.checkCollisions = false;
  13867. this.applyGravity = false;
  13868. this._collider = new BABYLON.Collider();
  13869. this._needMoveForGravity = false;
  13870. this._oldPosition = BABYLON.Vector3.Zero();
  13871. this._diffPosition = BABYLON.Vector3.Zero();
  13872. this._newPosition = BABYLON.Vector3.Zero();
  13873. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13874. if (collidedMesh === void 0) { collidedMesh = null; }
  13875. //TODO move this to the collision coordinator!
  13876. if (_this.getScene().workerCollisions)
  13877. newPosition.multiplyInPlace(_this._collider.radius);
  13878. var updatePosition = function (newPos) {
  13879. _this._newPosition.copyFrom(newPos);
  13880. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  13881. var oldPosition = _this.position.clone();
  13882. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  13883. _this.position.addInPlace(_this._diffPosition);
  13884. if (_this.onCollide && collidedMesh) {
  13885. _this.onCollide(collidedMesh);
  13886. }
  13887. }
  13888. };
  13889. updatePosition(newPosition);
  13890. };
  13891. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  13892. this.inputs.addKeyboard().addMouse();
  13893. }
  13894. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13895. //-- begin properties for backward compatibility for inputs
  13896. get: function () {
  13897. var mouse = this.inputs.attached["mouse"];
  13898. if (mouse)
  13899. return mouse.angularSensibility;
  13900. },
  13901. set: function (value) {
  13902. var mouse = this.inputs.attached["mouse"];
  13903. if (mouse)
  13904. mouse.angularSensibility = value;
  13905. },
  13906. enumerable: true,
  13907. configurable: true
  13908. });
  13909. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13910. get: function () {
  13911. var keyboard = this.inputs.attached["keyboard"];
  13912. if (keyboard)
  13913. return keyboard.keysUp;
  13914. },
  13915. set: function (value) {
  13916. var keyboard = this.inputs.attached["keyboard"];
  13917. if (keyboard)
  13918. keyboard.keysUp = value;
  13919. },
  13920. enumerable: true,
  13921. configurable: true
  13922. });
  13923. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13924. get: function () {
  13925. var keyboard = this.inputs.attached["keyboard"];
  13926. if (keyboard)
  13927. return keyboard.keysDown;
  13928. },
  13929. set: function (value) {
  13930. var keyboard = this.inputs.attached["keyboard"];
  13931. if (keyboard)
  13932. keyboard.keysDown = value;
  13933. },
  13934. enumerable: true,
  13935. configurable: true
  13936. });
  13937. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13938. get: function () {
  13939. var keyboard = this.inputs.attached["keyboard"];
  13940. if (keyboard)
  13941. return keyboard.keysLeft;
  13942. },
  13943. set: function (value) {
  13944. var keyboard = this.inputs.attached["keyboard"];
  13945. if (keyboard)
  13946. keyboard.keysLeft = value;
  13947. },
  13948. enumerable: true,
  13949. configurable: true
  13950. });
  13951. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13952. get: function () {
  13953. var keyboard = this.inputs.attached["keyboard"];
  13954. if (keyboard)
  13955. return keyboard.keysRight;
  13956. },
  13957. set: function (value) {
  13958. var keyboard = this.inputs.attached["keyboard"];
  13959. if (keyboard)
  13960. keyboard.keysRight = value;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. // Controls
  13966. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13967. this.inputs.attachElement(element, noPreventDefault);
  13968. };
  13969. FreeCamera.prototype.detachControl = function (element) {
  13970. this.inputs.detachElement(element);
  13971. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13972. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13973. };
  13974. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13975. var globalPosition;
  13976. if (this.parent) {
  13977. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13978. }
  13979. else {
  13980. globalPosition = this.position;
  13981. }
  13982. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13983. this._collider.radius = this.ellipsoid;
  13984. //no need for clone, as long as gravity is not on.
  13985. var actualVelocity = velocity;
  13986. //add gravity to the velocity to prevent the dual-collision checking
  13987. if (this.applyGravity) {
  13988. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13989. actualVelocity = velocity.add(this.getScene().gravity);
  13990. }
  13991. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13992. };
  13993. FreeCamera.prototype._checkInputs = function () {
  13994. if (!this._localDirection) {
  13995. this._localDirection = BABYLON.Vector3.Zero();
  13996. this._transformedDirection = BABYLON.Vector3.Zero();
  13997. }
  13998. this.inputs.checkInputs();
  13999. _super.prototype._checkInputs.call(this);
  14000. };
  14001. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14002. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14003. };
  14004. FreeCamera.prototype._updatePosition = function () {
  14005. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14006. this._collideWithWorld(this.cameraDirection);
  14007. }
  14008. else {
  14009. this.position.addInPlace(this.cameraDirection);
  14010. }
  14011. };
  14012. FreeCamera.prototype.dispose = function () {
  14013. this.inputs.clear();
  14014. _super.prototype.dispose.call(this);
  14015. };
  14016. FreeCamera.prototype.getTypeName = function () {
  14017. return "FreeCamera";
  14018. };
  14019. __decorate([
  14020. BABYLON.serializeAsVector3()
  14021. ], FreeCamera.prototype, "ellipsoid", void 0);
  14022. __decorate([
  14023. BABYLON.serialize()
  14024. ], FreeCamera.prototype, "checkCollisions", void 0);
  14025. __decorate([
  14026. BABYLON.serialize()
  14027. ], FreeCamera.prototype, "applyGravity", void 0);
  14028. return FreeCamera;
  14029. })(BABYLON.TargetCamera);
  14030. BABYLON.FreeCamera = FreeCamera;
  14031. })(BABYLON || (BABYLON = {}));
  14032. var BABYLON;
  14033. (function (BABYLON) {
  14034. var FreeCameraInputsManager = (function (_super) {
  14035. __extends(FreeCameraInputsManager, _super);
  14036. function FreeCameraInputsManager(camera) {
  14037. _super.call(this, camera);
  14038. }
  14039. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14040. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14041. return this;
  14042. };
  14043. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14044. if (touchEnabled === void 0) { touchEnabled = true; }
  14045. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14046. return this;
  14047. };
  14048. FreeCameraInputsManager.prototype.addGamepad = function () {
  14049. this.add(new BABYLON.FreeCameraGamepadInput());
  14050. return this;
  14051. };
  14052. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14053. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14054. return this;
  14055. };
  14056. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14057. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  14058. return this;
  14059. };
  14060. FreeCameraInputsManager.prototype.addTouch = function () {
  14061. this.add(new BABYLON.FreeCameraTouchInput());
  14062. return this;
  14063. };
  14064. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14065. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14066. return this;
  14067. };
  14068. return FreeCameraInputsManager;
  14069. })(BABYLON.CameraInputsManager);
  14070. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14071. })(BABYLON || (BABYLON = {}));
  14072. var BABYLON;
  14073. (function (BABYLON) {
  14074. var FollowCamera = (function (_super) {
  14075. __extends(FollowCamera, _super);
  14076. function FollowCamera(name, position, scene, target) {
  14077. _super.call(this, name, position, scene);
  14078. this.radius = 12;
  14079. this.rotationOffset = 0;
  14080. this.heightOffset = 4;
  14081. this.cameraAcceleration = 0.05;
  14082. this.maxCameraSpeed = 20;
  14083. this.target = target;
  14084. }
  14085. FollowCamera.prototype.getRadians = function (degrees) {
  14086. return degrees * Math.PI / 180;
  14087. };
  14088. FollowCamera.prototype.follow = function (cameraTarget) {
  14089. if (!cameraTarget)
  14090. return;
  14091. var yRotation;
  14092. if (cameraTarget.rotationQuaternion) {
  14093. var rotMatrix = new BABYLON.Matrix();
  14094. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14095. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14096. }
  14097. else {
  14098. yRotation = cameraTarget.rotation.y;
  14099. }
  14100. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14101. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14102. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14103. var dx = targetX - this.position.x;
  14104. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14105. var dz = (targetZ) - this.position.z;
  14106. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14107. var vy = dy * this.cameraAcceleration;
  14108. var vz = dz * this.cameraAcceleration * 2;
  14109. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14110. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14111. }
  14112. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14113. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14114. }
  14115. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14116. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14117. }
  14118. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14119. this.setTarget(cameraTarget.position);
  14120. };
  14121. FollowCamera.prototype._checkInputs = function () {
  14122. _super.prototype._checkInputs.call(this);
  14123. this.follow(this.target);
  14124. };
  14125. FollowCamera.prototype.getTypeName = function () {
  14126. return "FollowCamera";
  14127. };
  14128. __decorate([
  14129. BABYLON.serialize()
  14130. ], FollowCamera.prototype, "radius", void 0);
  14131. __decorate([
  14132. BABYLON.serialize()
  14133. ], FollowCamera.prototype, "rotationOffset", void 0);
  14134. __decorate([
  14135. BABYLON.serialize()
  14136. ], FollowCamera.prototype, "heightOffset", void 0);
  14137. __decorate([
  14138. BABYLON.serialize()
  14139. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14140. __decorate([
  14141. BABYLON.serialize()
  14142. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14143. __decorate([
  14144. BABYLON.serializeAsMeshReference("lockedTargetId")
  14145. ], FollowCamera.prototype, "target", void 0);
  14146. return FollowCamera;
  14147. })(BABYLON.TargetCamera);
  14148. BABYLON.FollowCamera = FollowCamera;
  14149. var ArcFollowCamera = (function (_super) {
  14150. __extends(ArcFollowCamera, _super);
  14151. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14152. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14153. this.alpha = alpha;
  14154. this.beta = beta;
  14155. this.radius = radius;
  14156. this.target = target;
  14157. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14158. this.follow();
  14159. }
  14160. ArcFollowCamera.prototype.follow = function () {
  14161. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14162. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14163. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14164. this.position = this.target.position.add(this._cartesianCoordinates);
  14165. this.setTarget(this.target.position);
  14166. };
  14167. ArcFollowCamera.prototype._checkInputs = function () {
  14168. _super.prototype._checkInputs.call(this);
  14169. this.follow();
  14170. };
  14171. ArcFollowCamera.prototype.getTypeName = function () {
  14172. return "ArcFollowCamera";
  14173. };
  14174. return ArcFollowCamera;
  14175. })(BABYLON.TargetCamera);
  14176. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14177. })(BABYLON || (BABYLON = {}));
  14178. var BABYLON;
  14179. (function (BABYLON) {
  14180. // We're mainly based on the logic defined into the FreeCamera code
  14181. var TouchCamera = (function (_super) {
  14182. __extends(TouchCamera, _super);
  14183. //-- end properties for backward compatibility for inputs
  14184. function TouchCamera(name, position, scene) {
  14185. _super.call(this, name, position, scene);
  14186. this.inputs.addTouch();
  14187. this._setupInputs();
  14188. }
  14189. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14190. //-- Begin properties for backward compatibility for inputs
  14191. get: function () {
  14192. var touch = this.inputs.attached["touch"];
  14193. if (touch)
  14194. return touch.touchAngularSensibility;
  14195. },
  14196. set: function (value) {
  14197. var touch = this.inputs.attached["touch"];
  14198. if (touch)
  14199. touch.touchAngularSensibility = value;
  14200. },
  14201. enumerable: true,
  14202. configurable: true
  14203. });
  14204. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14205. get: function () {
  14206. var touch = this.inputs.attached["touch"];
  14207. if (touch)
  14208. return touch.touchMoveSensibility;
  14209. },
  14210. set: function (value) {
  14211. var touch = this.inputs.attached["touch"];
  14212. if (touch)
  14213. touch.touchMoveSensibility = value;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. TouchCamera.prototype.getTypeName = function () {
  14219. return "TouchCamera";
  14220. };
  14221. TouchCamera.prototype._setupInputs = function () {
  14222. var mouse = this.inputs.attached["mouse"];
  14223. if (mouse) {
  14224. mouse.touchEnabled = false;
  14225. }
  14226. };
  14227. return TouchCamera;
  14228. })(BABYLON.FreeCamera);
  14229. BABYLON.TouchCamera = TouchCamera;
  14230. })(BABYLON || (BABYLON = {}));
  14231. var BABYLON;
  14232. (function (BABYLON) {
  14233. var ArcRotateCamera = (function (_super) {
  14234. __extends(ArcRotateCamera, _super);
  14235. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14236. var _this = this;
  14237. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14238. this.inertialAlphaOffset = 0;
  14239. this.inertialBetaOffset = 0;
  14240. this.inertialRadiusOffset = 0;
  14241. this.lowerAlphaLimit = null;
  14242. this.upperAlphaLimit = null;
  14243. this.lowerBetaLimit = 0.01;
  14244. this.upperBetaLimit = Math.PI;
  14245. this.lowerRadiusLimit = null;
  14246. this.upperRadiusLimit = null;
  14247. this.inertialPanningX = 0;
  14248. this.inertialPanningY = 0;
  14249. //-- end properties for backward compatibility for inputs
  14250. this.zoomOnFactor = 1;
  14251. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14252. this.allowUpsideDown = true;
  14253. this._viewMatrix = new BABYLON.Matrix();
  14254. // Panning
  14255. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14256. this.checkCollisions = false;
  14257. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14258. this._collider = new BABYLON.Collider();
  14259. this._previousPosition = BABYLON.Vector3.Zero();
  14260. this._collisionVelocity = BABYLON.Vector3.Zero();
  14261. this._newPosition = BABYLON.Vector3.Zero();
  14262. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14263. if (collidedMesh === void 0) { collidedMesh = null; }
  14264. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14265. newPosition.multiplyInPlace(_this._collider.radius);
  14266. }
  14267. if (!collidedMesh) {
  14268. _this._previousPosition.copyFrom(_this.position);
  14269. }
  14270. else {
  14271. _this.setPosition(newPosition);
  14272. if (_this.onCollide) {
  14273. _this.onCollide(collidedMesh);
  14274. }
  14275. }
  14276. // Recompute because of constraints
  14277. var cosa = Math.cos(_this.alpha);
  14278. var sina = Math.sin(_this.alpha);
  14279. var cosb = Math.cos(_this.beta);
  14280. var sinb = Math.sin(_this.beta);
  14281. if (sinb === 0) {
  14282. sinb = 0.0001;
  14283. }
  14284. var target = _this._getTargetPosition();
  14285. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14286. _this.position.copyFrom(_this._newPosition);
  14287. var up = _this.upVector;
  14288. if (_this.allowUpsideDown && _this.beta < 0) {
  14289. up = up.clone();
  14290. up = up.negate();
  14291. }
  14292. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14293. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14294. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14295. _this._collisionTriggered = false;
  14296. };
  14297. if (!target) {
  14298. this.target = BABYLON.Vector3.Zero();
  14299. }
  14300. else {
  14301. this.target = target;
  14302. }
  14303. this.alpha = alpha;
  14304. this.beta = beta;
  14305. this.radius = radius;
  14306. this.getViewMatrix();
  14307. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14308. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14309. }
  14310. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14311. //-- begin properties for backward compatibility for inputs
  14312. get: function () {
  14313. var pointers = this.inputs.attached["pointers"];
  14314. if (pointers)
  14315. return pointers.angularSensibilityX;
  14316. },
  14317. set: function (value) {
  14318. var pointers = this.inputs.attached["pointers"];
  14319. if (pointers) {
  14320. pointers.angularSensibilityX = value;
  14321. }
  14322. },
  14323. enumerable: true,
  14324. configurable: true
  14325. });
  14326. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14327. get: function () {
  14328. var pointers = this.inputs.attached["pointers"];
  14329. if (pointers)
  14330. return pointers.angularSensibilityY;
  14331. },
  14332. set: function (value) {
  14333. var pointers = this.inputs.attached["pointers"];
  14334. if (pointers) {
  14335. pointers.angularSensibilityY = value;
  14336. }
  14337. },
  14338. enumerable: true,
  14339. configurable: true
  14340. });
  14341. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14342. get: function () {
  14343. var pointers = this.inputs.attached["pointers"];
  14344. if (pointers)
  14345. return pointers.pinchPrecision;
  14346. },
  14347. set: function (value) {
  14348. var pointers = this.inputs.attached["pointers"];
  14349. if (pointers) {
  14350. pointers.pinchPrecision = value;
  14351. }
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14357. get: function () {
  14358. var pointers = this.inputs.attached["pointers"];
  14359. if (pointers)
  14360. return pointers.panningSensibility;
  14361. },
  14362. set: function (value) {
  14363. var pointers = this.inputs.attached["pointers"];
  14364. if (pointers) {
  14365. pointers.panningSensibility = value;
  14366. }
  14367. },
  14368. enumerable: true,
  14369. configurable: true
  14370. });
  14371. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14372. get: function () {
  14373. var keyboard = this.inputs.attached["keyboard"];
  14374. if (keyboard)
  14375. return keyboard.keysUp;
  14376. },
  14377. set: function (value) {
  14378. var keyboard = this.inputs.attached["keyboard"];
  14379. if (keyboard)
  14380. keyboard.keysUp = value;
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14386. get: function () {
  14387. var keyboard = this.inputs.attached["keyboard"];
  14388. if (keyboard)
  14389. return keyboard.keysDown;
  14390. },
  14391. set: function (value) {
  14392. var keyboard = this.inputs.attached["keyboard"];
  14393. if (keyboard)
  14394. keyboard.keysDown = value;
  14395. },
  14396. enumerable: true,
  14397. configurable: true
  14398. });
  14399. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14400. get: function () {
  14401. var keyboard = this.inputs.attached["keyboard"];
  14402. if (keyboard)
  14403. return keyboard.keysLeft;
  14404. },
  14405. set: function (value) {
  14406. var keyboard = this.inputs.attached["keyboard"];
  14407. if (keyboard)
  14408. keyboard.keysLeft = value;
  14409. },
  14410. enumerable: true,
  14411. configurable: true
  14412. });
  14413. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14414. get: function () {
  14415. var keyboard = this.inputs.attached["keyboard"];
  14416. if (keyboard)
  14417. return keyboard.keysRight;
  14418. },
  14419. set: function (value) {
  14420. var keyboard = this.inputs.attached["keyboard"];
  14421. if (keyboard)
  14422. keyboard.keysRight = value;
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14428. get: function () {
  14429. var mousewheel = this.inputs.attached["mousewheel"];
  14430. if (mousewheel)
  14431. return mousewheel.wheelPrecision;
  14432. },
  14433. set: function (value) {
  14434. var mousewheel = this.inputs.attached["mousewheel"];
  14435. if (mousewheel)
  14436. mousewheel.wheelPrecision = value;
  14437. },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. // Cache
  14442. ArcRotateCamera.prototype._initCache = function () {
  14443. _super.prototype._initCache.call(this);
  14444. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14445. this._cache.alpha = undefined;
  14446. this._cache.beta = undefined;
  14447. this._cache.radius = undefined;
  14448. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14449. };
  14450. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14451. if (!ignoreParentClass) {
  14452. _super.prototype._updateCache.call(this);
  14453. }
  14454. this._cache.target.copyFrom(this._getTargetPosition());
  14455. this._cache.alpha = this.alpha;
  14456. this._cache.beta = this.beta;
  14457. this._cache.radius = this.radius;
  14458. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14459. };
  14460. ArcRotateCamera.prototype._getTargetPosition = function () {
  14461. if (this.target.getAbsolutePosition) {
  14462. return this.target.getAbsolutePosition();
  14463. }
  14464. return this.target;
  14465. };
  14466. // Synchronized
  14467. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14468. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14469. return false;
  14470. return this._cache.target.equals(this.target)
  14471. && this._cache.alpha === this.alpha
  14472. && this._cache.beta === this.beta
  14473. && this._cache.radius === this.radius
  14474. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14475. };
  14476. // Methods
  14477. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14478. var _this = this;
  14479. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14480. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14481. this._useCtrlForPanning = useCtrlForPanning;
  14482. this._panningMouseButton = panningMouseButton;
  14483. this.inputs.attachElement(element, noPreventDefault);
  14484. this._reset = function () {
  14485. _this.inertialAlphaOffset = 0;
  14486. _this.inertialBetaOffset = 0;
  14487. _this.inertialRadiusOffset = 0;
  14488. };
  14489. };
  14490. ArcRotateCamera.prototype.detachControl = function (element) {
  14491. this.inputs.detachElement(element);
  14492. if (this._reset) {
  14493. this._reset();
  14494. }
  14495. };
  14496. ArcRotateCamera.prototype._checkInputs = function () {
  14497. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14498. if (this._collisionTriggered) {
  14499. return;
  14500. }
  14501. this.inputs.checkInputs();
  14502. console.log(this.name);
  14503. // Inertia
  14504. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14505. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14506. this.beta += this.inertialBetaOffset;
  14507. this.radius -= this.inertialRadiusOffset;
  14508. this.inertialAlphaOffset *= this.inertia;
  14509. this.inertialBetaOffset *= this.inertia;
  14510. this.inertialRadiusOffset *= this.inertia;
  14511. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14512. this.inertialAlphaOffset = 0;
  14513. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14514. this.inertialBetaOffset = 0;
  14515. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14516. this.inertialRadiusOffset = 0;
  14517. }
  14518. // Panning inertia
  14519. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14520. if (!this._localDirection) {
  14521. this._localDirection = BABYLON.Vector3.Zero();
  14522. this._transformedDirection = BABYLON.Vector3.Zero();
  14523. }
  14524. this.inertialPanningX *= this.inertia;
  14525. this.inertialPanningY *= this.inertia;
  14526. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14527. this.inertialPanningX = 0;
  14528. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14529. this.inertialPanningY = 0;
  14530. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14531. this._localDirection.multiplyInPlace(this.panningAxis);
  14532. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14533. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14534. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14535. if (!this.panningAxis.y) {
  14536. this._transformedDirection.y = 0;
  14537. }
  14538. if (!this.target.getAbsolutePosition) {
  14539. this.target.addInPlace(this._transformedDirection);
  14540. }
  14541. }
  14542. // Limits
  14543. this._checkLimits();
  14544. _super.prototype._checkInputs.call(this);
  14545. };
  14546. ArcRotateCamera.prototype._checkLimits = function () {
  14547. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14548. if (this.allowUpsideDown && this.beta > Math.PI) {
  14549. this.beta = this.beta - (2 * Math.PI);
  14550. }
  14551. }
  14552. else {
  14553. if (this.beta < this.lowerBetaLimit) {
  14554. this.beta = this.lowerBetaLimit;
  14555. }
  14556. }
  14557. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14558. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14559. this.beta = this.beta + (2 * Math.PI);
  14560. }
  14561. }
  14562. else {
  14563. if (this.beta > this.upperBetaLimit) {
  14564. this.beta = this.upperBetaLimit;
  14565. }
  14566. }
  14567. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14568. this.alpha = this.lowerAlphaLimit;
  14569. }
  14570. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14571. this.alpha = this.upperAlphaLimit;
  14572. }
  14573. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14574. this.radius = this.lowerRadiusLimit;
  14575. }
  14576. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14577. this.radius = this.upperRadiusLimit;
  14578. }
  14579. };
  14580. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14581. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14582. this.radius = radiusv3.length();
  14583. // Alpha
  14584. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14585. if (radiusv3.z < 0) {
  14586. this.alpha = 2 * Math.PI - this.alpha;
  14587. }
  14588. // Beta
  14589. this.beta = Math.acos(radiusv3.y / this.radius);
  14590. this._checkLimits();
  14591. };
  14592. ArcRotateCamera.prototype.setPosition = function (position) {
  14593. if (this.position.equals(position)) {
  14594. return;
  14595. }
  14596. this.position.copyFrom(position);
  14597. this.rebuildAnglesAndRadius();
  14598. };
  14599. ArcRotateCamera.prototype.setTarget = function (target) {
  14600. if (this._getTargetPosition().equals(target)) {
  14601. return;
  14602. }
  14603. this.target = target;
  14604. this.rebuildAnglesAndRadius();
  14605. };
  14606. ArcRotateCamera.prototype._getViewMatrix = function () {
  14607. // Compute
  14608. var cosa = Math.cos(this.alpha);
  14609. var sina = Math.sin(this.alpha);
  14610. var cosb = Math.cos(this.beta);
  14611. var sinb = Math.sin(this.beta);
  14612. if (sinb === 0) {
  14613. sinb = 0.0001;
  14614. }
  14615. var target = this._getTargetPosition();
  14616. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14617. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14618. this._collider.radius = this.collisionRadius;
  14619. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14620. this._collisionTriggered = true;
  14621. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14622. }
  14623. else {
  14624. this.position.copyFrom(this._newPosition);
  14625. var up = this.upVector;
  14626. if (this.allowUpsideDown && this.beta < 0) {
  14627. up = up.clone();
  14628. up = up.negate();
  14629. }
  14630. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14631. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14632. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14633. }
  14634. return this._viewMatrix;
  14635. };
  14636. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14637. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14638. meshes = meshes || this.getScene().meshes;
  14639. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14640. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14641. this.radius = distance * this.zoomOnFactor;
  14642. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14643. };
  14644. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14645. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14646. var meshesOrMinMaxVector;
  14647. var distance;
  14648. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14649. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  14650. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  14651. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  14652. }
  14653. else {
  14654. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  14655. distance = meshesOrMinMaxVectorAndDistance.distance;
  14656. }
  14657. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  14658. if (!doNotUpdateMaxZ) {
  14659. this.maxZ = distance * 2;
  14660. }
  14661. };
  14662. /**
  14663. * @override
  14664. * Override Camera.createRigCamera
  14665. */
  14666. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14667. var alphaShift;
  14668. switch (this.cameraRigMode) {
  14669. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14670. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14671. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14672. case BABYLON.Camera.RIG_MODE_VR:
  14673. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  14674. break;
  14675. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14676. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  14677. break;
  14678. }
  14679. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  14680. rigCam._cameraRigParams = {};
  14681. return rigCam;
  14682. };
  14683. /**
  14684. * @override
  14685. * Override Camera._updateRigCameras
  14686. */
  14687. ArcRotateCamera.prototype._updateRigCameras = function () {
  14688. var camLeft = this._rigCameras[0];
  14689. var camRight = this._rigCameras[1];
  14690. camLeft.beta = camRight.beta = this.beta;
  14691. camLeft.radius = camRight.radius = this.radius;
  14692. switch (this.cameraRigMode) {
  14693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14695. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14696. case BABYLON.Camera.RIG_MODE_VR:
  14697. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14698. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14699. break;
  14700. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14701. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  14702. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  14703. break;
  14704. }
  14705. _super.prototype._updateRigCameras.call(this);
  14706. };
  14707. ArcRotateCamera.prototype.dispose = function () {
  14708. this.inputs.clear();
  14709. _super.prototype.dispose.call(this);
  14710. };
  14711. ArcRotateCamera.prototype.getTypeName = function () {
  14712. return "ArcRotateCamera";
  14713. };
  14714. __decorate([
  14715. BABYLON.serialize()
  14716. ], ArcRotateCamera.prototype, "alpha", void 0);
  14717. __decorate([
  14718. BABYLON.serialize()
  14719. ], ArcRotateCamera.prototype, "beta", void 0);
  14720. __decorate([
  14721. BABYLON.serialize()
  14722. ], ArcRotateCamera.prototype, "radius", void 0);
  14723. __decorate([
  14724. BABYLON.serializeAsVector3()
  14725. ], ArcRotateCamera.prototype, "target", void 0);
  14726. __decorate([
  14727. BABYLON.serialize()
  14728. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  14729. __decorate([
  14730. BABYLON.serialize()
  14731. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  14732. __decorate([
  14733. BABYLON.serialize()
  14734. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  14735. __decorate([
  14736. BABYLON.serialize()
  14737. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  14738. __decorate([
  14739. BABYLON.serialize()
  14740. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  14741. __decorate([
  14742. BABYLON.serialize()
  14743. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  14744. __decorate([
  14745. BABYLON.serialize()
  14746. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  14747. __decorate([
  14748. BABYLON.serialize()
  14749. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  14750. __decorate([
  14751. BABYLON.serialize()
  14752. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  14753. __decorate([
  14754. BABYLON.serialize()
  14755. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  14756. __decorate([
  14757. BABYLON.serialize()
  14758. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  14759. __decorate([
  14760. BABYLON.serialize()
  14761. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  14762. __decorate([
  14763. BABYLON.serialize()
  14764. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  14765. return ArcRotateCamera;
  14766. })(BABYLON.TargetCamera);
  14767. BABYLON.ArcRotateCamera = ArcRotateCamera;
  14768. })(BABYLON || (BABYLON = {}));
  14769. var BABYLON;
  14770. (function (BABYLON) {
  14771. var ArcRotateCameraInputsManager = (function (_super) {
  14772. __extends(ArcRotateCameraInputsManager, _super);
  14773. function ArcRotateCameraInputsManager(camera) {
  14774. _super.call(this, camera);
  14775. }
  14776. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  14777. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  14778. return this;
  14779. };
  14780. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  14781. this.add(new BABYLON.ArcRotateCameraPointersInput());
  14782. return this;
  14783. };
  14784. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  14785. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  14786. return this;
  14787. };
  14788. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  14789. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  14790. return this;
  14791. };
  14792. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  14793. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  14794. return this;
  14795. };
  14796. return ArcRotateCameraInputsManager;
  14797. })(BABYLON.CameraInputsManager);
  14798. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  14799. })(BABYLON || (BABYLON = {}));
  14800. var BABYLON;
  14801. (function (BABYLON) {
  14802. var RenderingManager = (function () {
  14803. function RenderingManager(scene) {
  14804. this._renderingGroups = new Array();
  14805. this._scene = scene;
  14806. }
  14807. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  14808. if (this._scene._activeParticleSystems.length === 0) {
  14809. return;
  14810. }
  14811. // Particles
  14812. var activeCamera = this._scene.activeCamera;
  14813. this._scene._particlesDuration.beginMonitoring();
  14814. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14815. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14816. if (particleSystem.renderingGroupId !== index) {
  14817. continue;
  14818. }
  14819. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14820. continue;
  14821. }
  14822. this._clearDepthBuffer();
  14823. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14824. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14825. }
  14826. }
  14827. this._scene._particlesDuration.endMonitoring(false);
  14828. };
  14829. RenderingManager.prototype._renderSprites = function (index) {
  14830. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  14831. return;
  14832. }
  14833. // Sprites
  14834. var activeCamera = this._scene.activeCamera;
  14835. this._scene._spritesDuration.beginMonitoring();
  14836. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  14837. var spriteManager = this._scene.spriteManagers[id];
  14838. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14839. this._clearDepthBuffer();
  14840. spriteManager.render();
  14841. }
  14842. }
  14843. this._scene._spritesDuration.endMonitoring(false);
  14844. };
  14845. RenderingManager.prototype._clearDepthBuffer = function () {
  14846. if (this._depthBufferAlreadyCleaned) {
  14847. return;
  14848. }
  14849. this._scene.getEngine().clear(0, false, true);
  14850. this._depthBufferAlreadyCleaned = true;
  14851. };
  14852. RenderingManager.prototype._renderSpritesAndParticles = function () {
  14853. if (this._currentRenderSprites) {
  14854. this._renderSprites(this._currentIndex);
  14855. }
  14856. if (this._currentRenderParticles) {
  14857. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  14858. }
  14859. };
  14860. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14861. this._currentActiveMeshes = activeMeshes;
  14862. this._currentRenderParticles = renderParticles;
  14863. this._currentRenderSprites = renderSprites;
  14864. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14865. this._depthBufferAlreadyCleaned = index === 0;
  14866. var renderingGroup = this._renderingGroups[index];
  14867. var needToStepBack = false;
  14868. this._currentIndex = index;
  14869. if (renderingGroup) {
  14870. this._clearDepthBuffer();
  14871. if (!renderingGroup.onBeforeTransparentRendering) {
  14872. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  14873. }
  14874. if (!renderingGroup.render(customRenderFunction)) {
  14875. this._renderingGroups.splice(index, 1);
  14876. needToStepBack = true;
  14877. this._renderSpritesAndParticles();
  14878. }
  14879. }
  14880. else {
  14881. this._renderSpritesAndParticles();
  14882. }
  14883. if (needToStepBack) {
  14884. index--;
  14885. }
  14886. }
  14887. };
  14888. RenderingManager.prototype.reset = function () {
  14889. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  14890. if (renderingGroup) {
  14891. renderingGroup.prepare();
  14892. }
  14893. });
  14894. };
  14895. RenderingManager.prototype.dispatch = function (subMesh) {
  14896. var mesh = subMesh.getMesh();
  14897. var renderingGroupId = mesh.renderingGroupId || 0;
  14898. if (!this._renderingGroups[renderingGroupId]) {
  14899. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  14900. }
  14901. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14902. };
  14903. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14904. return RenderingManager;
  14905. })();
  14906. BABYLON.RenderingManager = RenderingManager;
  14907. })(BABYLON || (BABYLON = {}));
  14908. var BABYLON;
  14909. (function (BABYLON) {
  14910. var RenderingGroup = (function () {
  14911. function RenderingGroup(index, scene) {
  14912. this.index = index;
  14913. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14914. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14915. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14916. this._scene = scene;
  14917. }
  14918. RenderingGroup.prototype.render = function (customRenderFunction) {
  14919. if (customRenderFunction) {
  14920. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14921. return true;
  14922. }
  14923. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14924. if (this.onBeforeTransparentRendering) {
  14925. this.onBeforeTransparentRendering();
  14926. }
  14927. return false;
  14928. }
  14929. var engine = this._scene.getEngine();
  14930. // Opaque
  14931. var subIndex;
  14932. var submesh;
  14933. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14934. submesh = this._opaqueSubMeshes.data[subIndex];
  14935. submesh.render(false);
  14936. }
  14937. // Alpha test
  14938. engine.setAlphaTesting(true);
  14939. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14940. submesh = this._alphaTestSubMeshes.data[subIndex];
  14941. submesh.render(false);
  14942. }
  14943. engine.setAlphaTesting(false);
  14944. if (this.onBeforeTransparentRendering) {
  14945. this.onBeforeTransparentRendering();
  14946. }
  14947. // Transparent
  14948. if (this._transparentSubMeshes.length) {
  14949. // Sorting
  14950. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14951. submesh = this._transparentSubMeshes.data[subIndex];
  14952. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14953. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14954. }
  14955. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14956. sortedArray.sort(function (a, b) {
  14957. // Alpha index first
  14958. if (a._alphaIndex > b._alphaIndex) {
  14959. return 1;
  14960. }
  14961. if (a._alphaIndex < b._alphaIndex) {
  14962. return -1;
  14963. }
  14964. // Then distance to camera
  14965. if (a._distanceToCamera < b._distanceToCamera) {
  14966. return 1;
  14967. }
  14968. if (a._distanceToCamera > b._distanceToCamera) {
  14969. return -1;
  14970. }
  14971. return 0;
  14972. });
  14973. // Rendering
  14974. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14975. submesh = sortedArray[subIndex];
  14976. submesh.render(true);
  14977. }
  14978. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14979. }
  14980. return true;
  14981. };
  14982. RenderingGroup.prototype.prepare = function () {
  14983. this._opaqueSubMeshes.reset();
  14984. this._transparentSubMeshes.reset();
  14985. this._alphaTestSubMeshes.reset();
  14986. };
  14987. RenderingGroup.prototype.dispatch = function (subMesh) {
  14988. var material = subMesh.getMaterial();
  14989. var mesh = subMesh.getMesh();
  14990. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14991. this._transparentSubMeshes.push(subMesh);
  14992. }
  14993. else if (material.needAlphaTesting()) {
  14994. this._alphaTestSubMeshes.push(subMesh);
  14995. }
  14996. else {
  14997. this._opaqueSubMeshes.push(subMesh); // Opaque
  14998. }
  14999. };
  15000. return RenderingGroup;
  15001. })();
  15002. BABYLON.RenderingGroup = RenderingGroup;
  15003. })(BABYLON || (BABYLON = {}));
  15004. var BABYLON;
  15005. (function (BABYLON) {
  15006. var PointerEventTypes = (function () {
  15007. function PointerEventTypes() {
  15008. }
  15009. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15010. get: function () {
  15011. return PointerEventTypes._POINTERDOWN;
  15012. },
  15013. enumerable: true,
  15014. configurable: true
  15015. });
  15016. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15017. get: function () {
  15018. return PointerEventTypes._POINTERUP;
  15019. },
  15020. enumerable: true,
  15021. configurable: true
  15022. });
  15023. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15024. get: function () {
  15025. return PointerEventTypes._POINTERMOVE;
  15026. },
  15027. enumerable: true,
  15028. configurable: true
  15029. });
  15030. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15031. get: function () {
  15032. return PointerEventTypes._POINTERWHEEL;
  15033. },
  15034. enumerable: true,
  15035. configurable: true
  15036. });
  15037. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15038. get: function () {
  15039. return PointerEventTypes._POINTERPICK;
  15040. },
  15041. enumerable: true,
  15042. configurable: true
  15043. });
  15044. PointerEventTypes._POINTERDOWN = 0x01;
  15045. PointerEventTypes._POINTERUP = 0x02;
  15046. PointerEventTypes._POINTERMOVE = 0x04;
  15047. PointerEventTypes._POINTERWHEEL = 0x08;
  15048. PointerEventTypes._POINTERPICK = 0x10;
  15049. return PointerEventTypes;
  15050. })();
  15051. BABYLON.PointerEventTypes = PointerEventTypes;
  15052. var PointerInfoBase = (function () {
  15053. function PointerInfoBase(type, event) {
  15054. this.type = type;
  15055. this.event = event;
  15056. }
  15057. return PointerInfoBase;
  15058. })();
  15059. BABYLON.PointerInfoBase = PointerInfoBase;
  15060. /**
  15061. * This class is used to store pointer related info for the onPrePointerObservable event.
  15062. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15063. */
  15064. var PointerInfoPre = (function (_super) {
  15065. __extends(PointerInfoPre, _super);
  15066. function PointerInfoPre(type, event, localX, localY) {
  15067. _super.call(this, type, event);
  15068. this.skipOnPointerObservable = false;
  15069. this.localPosition = new BABYLON.Vector2(localX, localY);
  15070. }
  15071. return PointerInfoPre;
  15072. })(PointerInfoBase);
  15073. BABYLON.PointerInfoPre = PointerInfoPre;
  15074. /**
  15075. * This type contains all the data related to a pointer event in Babylon.js.
  15076. * 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.
  15077. */
  15078. var PointerInfo = (function (_super) {
  15079. __extends(PointerInfo, _super);
  15080. function PointerInfo(type, event, pickInfo) {
  15081. _super.call(this, type, event);
  15082. this.pickInfo = pickInfo;
  15083. }
  15084. return PointerInfo;
  15085. })(PointerInfoBase);
  15086. BABYLON.PointerInfo = PointerInfo;
  15087. /**
  15088. * Represents a scene to be rendered by the engine.
  15089. * @see http://doc.babylonjs.com/page.php?p=21911
  15090. */
  15091. var Scene = (function () {
  15092. /**
  15093. * @constructor
  15094. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15095. */
  15096. function Scene(engine) {
  15097. // Members
  15098. this.autoClear = true;
  15099. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15100. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15101. this.forceWireframe = false;
  15102. this.forcePointsCloud = false;
  15103. this.forceShowBoundingBoxes = false;
  15104. this.animationsEnabled = true;
  15105. this.constantlyUpdateMeshUnderPointer = false;
  15106. this.hoverCursor = "pointer";
  15107. // Events
  15108. /**
  15109. * An event triggered when the scene is disposed.
  15110. * @type {BABYLON.Observable}
  15111. */
  15112. this.onDisposeObservable = new BABYLON.Observable();
  15113. /**
  15114. * An event triggered before rendering the scene
  15115. * @type {BABYLON.Observable}
  15116. */
  15117. this.onBeforeRenderObservable = new BABYLON.Observable();
  15118. /**
  15119. * An event triggered after rendering the scene
  15120. * @type {BABYLON.Observable}
  15121. */
  15122. this.onAfterRenderObservable = new BABYLON.Observable();
  15123. /**
  15124. * An event triggered when the scene is ready
  15125. * @type {BABYLON.Observable}
  15126. */
  15127. this.onReadyObservable = new BABYLON.Observable();
  15128. /**
  15129. * An event triggered before rendering a camera
  15130. * @type {BABYLON.Observable}
  15131. */
  15132. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15133. /**
  15134. * An event triggered after rendering a camera
  15135. * @type {BABYLON.Observable}
  15136. */
  15137. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15138. /**
  15139. * An event triggered when a camera is created
  15140. * @type {BABYLON.Observable}
  15141. */
  15142. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15143. /**
  15144. * An event triggered when a camera is removed
  15145. * @type {BABYLON.Observable}
  15146. */
  15147. this.onCameraRemovedObservable = new BABYLON.Observable();
  15148. /**
  15149. * An event triggered when a light is created
  15150. * @type {BABYLON.Observable}
  15151. */
  15152. this.onNewLightAddedObservable = new BABYLON.Observable();
  15153. /**
  15154. * An event triggered when a light is removed
  15155. * @type {BABYLON.Observable}
  15156. */
  15157. this.onLightRemovedObservable = new BABYLON.Observable();
  15158. /**
  15159. * An event triggered when a geometry is created
  15160. * @type {BABYLON.Observable}
  15161. */
  15162. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15163. /**
  15164. * An event triggered when a geometry is removed
  15165. * @type {BABYLON.Observable}
  15166. */
  15167. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15168. /**
  15169. * An event triggered when a mesh is created
  15170. * @type {BABYLON.Observable}
  15171. */
  15172. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15173. /**
  15174. * An event triggered when a mesh is removed
  15175. * @type {BABYLON.Observable}
  15176. */
  15177. this.onMeshRemovedObservable = new BABYLON.Observable();
  15178. // Animations
  15179. this.animations = [];
  15180. /**
  15181. * 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).
  15182. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15183. */
  15184. this.onPrePointerObservable = new BABYLON.Observable();
  15185. /**
  15186. * Observable event triggered each time an input event is received from the rendering canvas
  15187. */
  15188. this.onPointerObservable = new BABYLON.Observable();
  15189. 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
  15190. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15191. this._startingPointerTime = 0;
  15192. // Fog
  15193. /**
  15194. * is fog enabled on this scene.
  15195. * @type {boolean}
  15196. */
  15197. this.fogEnabled = true;
  15198. this.fogMode = Scene.FOGMODE_NONE;
  15199. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15200. this.fogDensity = 0.1;
  15201. this.fogStart = 0;
  15202. this.fogEnd = 1000.0;
  15203. // Lights
  15204. /**
  15205. * is shadow enabled on this scene.
  15206. * @type {boolean}
  15207. */
  15208. this.shadowsEnabled = true;
  15209. /**
  15210. * is light enabled on this scene.
  15211. * @type {boolean}
  15212. */
  15213. this.lightsEnabled = true;
  15214. /**
  15215. * All of the lights added to this scene.
  15216. * @see BABYLON.Light
  15217. * @type {BABYLON.Light[]}
  15218. */
  15219. this.lights = new Array();
  15220. // Cameras
  15221. /**
  15222. * All of the cameras added to this scene.
  15223. * @see BABYLON.Camera
  15224. * @type {BABYLON.Camera[]}
  15225. */
  15226. this.cameras = new Array();
  15227. this.activeCameras = new Array();
  15228. // Meshes
  15229. /**
  15230. * All of the (abstract) meshes added to this scene.
  15231. * @see BABYLON.AbstractMesh
  15232. * @type {BABYLON.AbstractMesh[]}
  15233. */
  15234. this.meshes = new Array();
  15235. // Geometries
  15236. this._geometries = new Array();
  15237. this.materials = new Array();
  15238. this.multiMaterials = new Array();
  15239. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15240. // Textures
  15241. this.texturesEnabled = true;
  15242. this.textures = new Array();
  15243. // Particles
  15244. this.particlesEnabled = true;
  15245. this.particleSystems = new Array();
  15246. // Sprites
  15247. this.spritesEnabled = true;
  15248. this.spriteManagers = new Array();
  15249. // Layers
  15250. this.layers = new Array();
  15251. // Skeletons
  15252. this.skeletonsEnabled = true;
  15253. this.skeletons = new Array();
  15254. // Lens flares
  15255. this.lensFlaresEnabled = true;
  15256. this.lensFlareSystems = new Array();
  15257. // Collisions
  15258. this.collisionsEnabled = true;
  15259. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15260. // Postprocesses
  15261. this.postProcessesEnabled = true;
  15262. // Customs render targets
  15263. this.renderTargetsEnabled = true;
  15264. this.dumpNextRenderTargets = false;
  15265. this.customRenderTargets = new Array();
  15266. // Imported meshes
  15267. this.importedMeshesFiles = new Array();
  15268. // Probes
  15269. this.probesEnabled = true;
  15270. this.reflectionProbes = new Array();
  15271. this._actionManagers = new Array();
  15272. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15273. // Procedural textures
  15274. this.proceduralTexturesEnabled = true;
  15275. this._proceduralTextures = new Array();
  15276. this.soundTracks = new Array();
  15277. this._audioEnabled = true;
  15278. this._headphone = false;
  15279. // Performance counters
  15280. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15281. this._totalLightsCounter = new BABYLON.PerfCounter();
  15282. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15283. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15284. this._totalVertices = new BABYLON.PerfCounter();
  15285. this._activeIndices = new BABYLON.PerfCounter();
  15286. this._activeParticles = new BABYLON.PerfCounter();
  15287. this._lastFrameDuration = new BABYLON.PerfCounter();
  15288. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15289. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15290. this._particlesDuration = new BABYLON.PerfCounter();
  15291. this._renderDuration = new BABYLON.PerfCounter();
  15292. this._spritesDuration = new BABYLON.PerfCounter();
  15293. this._activeBones = new BABYLON.PerfCounter();
  15294. this._renderId = 0;
  15295. this._executeWhenReadyTimeoutId = -1;
  15296. this._intermediateRendering = false;
  15297. this._toBeDisposed = new BABYLON.SmartArray(256);
  15298. this._pendingData = []; //ANY
  15299. this._activeMeshes = new BABYLON.SmartArray(256);
  15300. this._processedMaterials = new BABYLON.SmartArray(256);
  15301. this._renderTargets = new BABYLON.SmartArray(256);
  15302. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15303. this._activeSkeletons = new BABYLON.SmartArray(32);
  15304. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15305. this._activeAnimatables = new Array();
  15306. this._transformMatrix = BABYLON.Matrix.Zero();
  15307. this._edgesRenderers = new BABYLON.SmartArray(16);
  15308. this._uniqueIdCounter = 0;
  15309. this._engine = engine;
  15310. engine.scenes.push(this);
  15311. this._renderingManager = new BABYLON.RenderingManager(this);
  15312. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15313. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15314. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15315. if (BABYLON.OutlineRenderer) {
  15316. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15317. }
  15318. this.attachControl();
  15319. if (BABYLON.SoundTrack) {
  15320. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15321. }
  15322. //simplification queue
  15323. if (BABYLON.SimplificationQueue) {
  15324. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15325. }
  15326. //collision coordinator initialization. For now legacy per default.
  15327. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15328. }
  15329. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15330. get: function () {
  15331. return Scene._FOGMODE_NONE;
  15332. },
  15333. enumerable: true,
  15334. configurable: true
  15335. });
  15336. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15337. get: function () {
  15338. return Scene._FOGMODE_EXP;
  15339. },
  15340. enumerable: true,
  15341. configurable: true
  15342. });
  15343. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15344. get: function () {
  15345. return Scene._FOGMODE_EXP2;
  15346. },
  15347. enumerable: true,
  15348. configurable: true
  15349. });
  15350. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15351. get: function () {
  15352. return Scene._FOGMODE_LINEAR;
  15353. },
  15354. enumerable: true,
  15355. configurable: true
  15356. });
  15357. Object.defineProperty(Scene.prototype, "onDispose", {
  15358. set: function (callback) {
  15359. if (this._onDisposeObserver) {
  15360. this.onDisposeObservable.remove(this._onDisposeObserver);
  15361. }
  15362. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15363. },
  15364. enumerable: true,
  15365. configurable: true
  15366. });
  15367. Object.defineProperty(Scene.prototype, "beforeRender", {
  15368. set: function (callback) {
  15369. if (this._onBeforeRenderObserver) {
  15370. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15371. }
  15372. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15373. },
  15374. enumerable: true,
  15375. configurable: true
  15376. });
  15377. Object.defineProperty(Scene.prototype, "afterRender", {
  15378. set: function (callback) {
  15379. if (this._onAfterRenderObserver) {
  15380. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15381. }
  15382. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15383. },
  15384. enumerable: true,
  15385. configurable: true
  15386. });
  15387. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15388. set: function (callback) {
  15389. if (this._onBeforeCameraRenderObserver) {
  15390. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15391. }
  15392. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15393. },
  15394. enumerable: true,
  15395. configurable: true
  15396. });
  15397. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15398. set: function (callback) {
  15399. if (this._onAfterCameraRenderObserver) {
  15400. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15401. }
  15402. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15403. },
  15404. enumerable: true,
  15405. configurable: true
  15406. });
  15407. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15408. get: function () {
  15409. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15410. },
  15411. enumerable: true,
  15412. configurable: true
  15413. });
  15414. Object.defineProperty(Scene.prototype, "debugLayer", {
  15415. // Properties
  15416. get: function () {
  15417. if (!this._debugLayer) {
  15418. this._debugLayer = new BABYLON.DebugLayer(this);
  15419. }
  15420. return this._debugLayer;
  15421. },
  15422. enumerable: true,
  15423. configurable: true
  15424. });
  15425. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15426. get: function () {
  15427. return this._workerCollisions;
  15428. },
  15429. set: function (enabled) {
  15430. enabled = (enabled && !!Worker);
  15431. this._workerCollisions = enabled;
  15432. if (this.collisionCoordinator) {
  15433. this.collisionCoordinator.destroy();
  15434. }
  15435. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15436. this.collisionCoordinator.init(this);
  15437. },
  15438. enumerable: true,
  15439. configurable: true
  15440. });
  15441. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15442. get: function () {
  15443. return this._selectionOctree;
  15444. },
  15445. enumerable: true,
  15446. configurable: true
  15447. });
  15448. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15449. /**
  15450. * The mesh that is currently under the pointer.
  15451. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15452. */
  15453. get: function () {
  15454. return this._pointerOverMesh;
  15455. },
  15456. enumerable: true,
  15457. configurable: true
  15458. });
  15459. Object.defineProperty(Scene.prototype, "pointerX", {
  15460. /**
  15461. * Current on-screen X position of the pointer
  15462. * @return {number} X position of the pointer
  15463. */
  15464. get: function () {
  15465. return this._pointerX;
  15466. },
  15467. enumerable: true,
  15468. configurable: true
  15469. });
  15470. Object.defineProperty(Scene.prototype, "pointerY", {
  15471. /**
  15472. * Current on-screen Y position of the pointer
  15473. * @return {number} Y position of the pointer
  15474. */
  15475. get: function () {
  15476. return this._pointerY;
  15477. },
  15478. enumerable: true,
  15479. configurable: true
  15480. });
  15481. Scene.prototype.getCachedMaterial = function () {
  15482. return this._cachedMaterial;
  15483. };
  15484. Scene.prototype.getBoundingBoxRenderer = function () {
  15485. return this._boundingBoxRenderer;
  15486. };
  15487. Scene.prototype.getOutlineRenderer = function () {
  15488. return this._outlineRenderer;
  15489. };
  15490. Scene.prototype.getEngine = function () {
  15491. return this._engine;
  15492. };
  15493. Scene.prototype.getTotalVertices = function () {
  15494. return this._totalVertices.current;
  15495. };
  15496. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15497. get: function () {
  15498. return this._totalVertices;
  15499. },
  15500. enumerable: true,
  15501. configurable: true
  15502. });
  15503. Scene.prototype.getActiveIndices = function () {
  15504. return this._activeIndices.current;
  15505. };
  15506. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15507. get: function () {
  15508. return this._activeIndices;
  15509. },
  15510. enumerable: true,
  15511. configurable: true
  15512. });
  15513. Scene.prototype.getActiveParticles = function () {
  15514. return this._activeParticles.current;
  15515. };
  15516. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15517. get: function () {
  15518. return this._activeParticles;
  15519. },
  15520. enumerable: true,
  15521. configurable: true
  15522. });
  15523. Scene.prototype.getActiveBones = function () {
  15524. return this._activeBones.current;
  15525. };
  15526. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15527. get: function () {
  15528. return this._activeBones;
  15529. },
  15530. enumerable: true,
  15531. configurable: true
  15532. });
  15533. // Stats
  15534. Scene.prototype.getLastFrameDuration = function () {
  15535. return this._lastFrameDuration.current;
  15536. };
  15537. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15538. get: function () {
  15539. return this._lastFrameDuration;
  15540. },
  15541. enumerable: true,
  15542. configurable: true
  15543. });
  15544. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15545. return this._evaluateActiveMeshesDuration.current;
  15546. };
  15547. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15548. get: function () {
  15549. return this._evaluateActiveMeshesDuration;
  15550. },
  15551. enumerable: true,
  15552. configurable: true
  15553. });
  15554. Scene.prototype.getActiveMeshes = function () {
  15555. return this._activeMeshes;
  15556. };
  15557. Scene.prototype.getRenderTargetsDuration = function () {
  15558. return this._renderTargetsDuration.current;
  15559. };
  15560. Scene.prototype.getRenderDuration = function () {
  15561. return this._renderDuration.current;
  15562. };
  15563. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15564. get: function () {
  15565. return this._renderDuration;
  15566. },
  15567. enumerable: true,
  15568. configurable: true
  15569. });
  15570. Scene.prototype.getParticlesDuration = function () {
  15571. return this._particlesDuration.current;
  15572. };
  15573. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15574. get: function () {
  15575. return this._particlesDuration;
  15576. },
  15577. enumerable: true,
  15578. configurable: true
  15579. });
  15580. Scene.prototype.getSpritesDuration = function () {
  15581. return this._spritesDuration.current;
  15582. };
  15583. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15584. get: function () {
  15585. return this._spritesDuration;
  15586. },
  15587. enumerable: true,
  15588. configurable: true
  15589. });
  15590. Scene.prototype.getAnimationRatio = function () {
  15591. return this._animationRatio;
  15592. };
  15593. Scene.prototype.getRenderId = function () {
  15594. return this._renderId;
  15595. };
  15596. Scene.prototype.incrementRenderId = function () {
  15597. this._renderId++;
  15598. };
  15599. Scene.prototype._updatePointerPosition = function (evt) {
  15600. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15601. this._pointerX = evt.clientX - canvasRect.left;
  15602. this._pointerY = evt.clientY - canvasRect.top;
  15603. this._unTranslatedPointerX = this._pointerX;
  15604. this._unTranslatedPointerY = this._pointerY;
  15605. if (this.cameraToUseForPointers) {
  15606. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15607. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15608. }
  15609. };
  15610. // Pointers handling
  15611. /**
  15612. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15613. * @param attachUp defines if you want to attach events to pointerup
  15614. * @param attachDown defines if you want to attach events to pointerdown
  15615. * @param attachMove defines if you want to attach events to pointermove
  15616. */
  15617. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15618. var _this = this;
  15619. if (attachUp === void 0) { attachUp = true; }
  15620. if (attachDown === void 0) { attachDown = true; }
  15621. if (attachMove === void 0) { attachMove = true; }
  15622. var spritePredicate = function (sprite) {
  15623. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15624. };
  15625. this._onPointerMove = function (evt) {
  15626. _this._updatePointerPosition(evt);
  15627. // PreObservable support
  15628. if (_this.onPrePointerObservable.hasObservers()) {
  15629. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15630. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15631. _this.onPrePointerObservable.notifyObservers(pi, type);
  15632. if (pi.skipOnPointerObservable) {
  15633. return;
  15634. }
  15635. }
  15636. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15637. return;
  15638. }
  15639. var canvas = _this._engine.getRenderingCanvas();
  15640. if (!_this.pointerMovePredicate) {
  15641. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  15642. }
  15643. // Meshes
  15644. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15645. if (pickResult.hit && pickResult.pickedMesh) {
  15646. _this.setPointerOverSprite(null);
  15647. _this.setPointerOverMesh(pickResult.pickedMesh);
  15648. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15649. canvas.style.cursor = _this.hoverCursor;
  15650. }
  15651. else {
  15652. canvas.style.cursor = "";
  15653. }
  15654. }
  15655. else {
  15656. _this.setPointerOverMesh(null);
  15657. // Sprites
  15658. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15659. if (pickResult.hit && pickResult.pickedSprite) {
  15660. canvas.style.cursor = _this.hoverCursor;
  15661. _this.setPointerOverSprite(pickResult.pickedSprite);
  15662. }
  15663. else {
  15664. _this.setPointerOverSprite(null);
  15665. // Restore pointer
  15666. canvas.style.cursor = "";
  15667. }
  15668. }
  15669. if (_this.onPointerMove) {
  15670. _this.onPointerMove(evt, pickResult);
  15671. }
  15672. if (_this.onPointerObservable.hasObservers()) {
  15673. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15674. var pi = new PointerInfo(type, evt, pickResult);
  15675. _this.onPointerObservable.notifyObservers(pi, type);
  15676. }
  15677. };
  15678. this._onPointerDown = function (evt) {
  15679. _this._updatePointerPosition(evt);
  15680. // PreObservable support
  15681. if (_this.onPrePointerObservable.hasObservers()) {
  15682. var type = PointerEventTypes.POINTERDOWN;
  15683. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15684. _this.onPrePointerObservable.notifyObservers(pi, type);
  15685. if (pi.skipOnPointerObservable) {
  15686. return;
  15687. }
  15688. }
  15689. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15690. return;
  15691. }
  15692. _this._startingPointerPosition.x = _this._pointerX;
  15693. _this._startingPointerPosition.y = _this._pointerY;
  15694. _this._startingPointerTime = new Date().getTime();
  15695. if (!_this.pointerDownPredicate) {
  15696. _this.pointerDownPredicate = function (mesh) {
  15697. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  15698. };
  15699. }
  15700. // Meshes
  15701. _this._pickedDownMesh = null;
  15702. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15703. if (pickResult.hit && pickResult.pickedMesh) {
  15704. if (pickResult.pickedMesh.actionManager) {
  15705. _this._pickedDownMesh = pickResult.pickedMesh;
  15706. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  15707. switch (evt.button) {
  15708. case 0:
  15709. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15710. break;
  15711. case 1:
  15712. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15713. break;
  15714. case 2:
  15715. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15716. break;
  15717. }
  15718. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15719. }
  15720. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15721. var that = _this;
  15722. window.setTimeout(function () {
  15723. 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);
  15724. if (pickResult.hit && pickResult.pickedMesh) {
  15725. if (pickResult.pickedMesh.actionManager) {
  15726. 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)) {
  15727. that._startingPointerTime = 0;
  15728. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15729. }
  15730. }
  15731. }
  15732. }, BABYLON.ActionManager.LongPressDelay);
  15733. }
  15734. }
  15735. }
  15736. if (_this.onPointerDown) {
  15737. _this.onPointerDown(evt, pickResult);
  15738. }
  15739. if (_this.onPointerObservable.hasObservers()) {
  15740. var type = PointerEventTypes.POINTERDOWN;
  15741. var pi = new PointerInfo(type, evt, pickResult);
  15742. _this.onPointerObservable.notifyObservers(pi, type);
  15743. }
  15744. // Sprites
  15745. _this._pickedDownSprite = null;
  15746. if (_this.spriteManagers.length > 0) {
  15747. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15748. if (pickResult.hit && pickResult.pickedSprite) {
  15749. if (pickResult.pickedSprite.actionManager) {
  15750. _this._pickedDownSprite = pickResult.pickedSprite;
  15751. switch (evt.button) {
  15752. case 0:
  15753. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15754. break;
  15755. case 1:
  15756. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15757. break;
  15758. case 2:
  15759. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15760. break;
  15761. }
  15762. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15763. }
  15764. }
  15765. }
  15766. };
  15767. this._onPointerUp = function (evt) {
  15768. _this._updatePointerPosition(evt);
  15769. // PreObservable support
  15770. if (_this.onPrePointerObservable.hasObservers()) {
  15771. var type = PointerEventTypes.POINTERUP;
  15772. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15773. _this.onPrePointerObservable.notifyObservers(pi, type);
  15774. if (pi.skipOnPointerObservable) {
  15775. return;
  15776. }
  15777. }
  15778. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15779. return;
  15780. }
  15781. if (!_this.pointerUpPredicate) {
  15782. _this.pointerUpPredicate = function (mesh) {
  15783. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  15784. };
  15785. }
  15786. // Meshes
  15787. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  15788. if (pickResult.hit && pickResult.pickedMesh) {
  15789. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  15790. if (_this.onPointerPick) {
  15791. _this.onPointerPick(evt, pickResult);
  15792. }
  15793. if (_this.onPointerObservable.hasObservers()) {
  15794. var type = PointerEventTypes.POINTERPICK;
  15795. var pi = new PointerInfo(type, evt, pickResult);
  15796. _this.onPointerObservable.notifyObservers(pi, type);
  15797. }
  15798. }
  15799. if (pickResult.pickedMesh.actionManager) {
  15800. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15801. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15802. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15803. }
  15804. }
  15805. }
  15806. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  15807. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  15808. }
  15809. if (_this.onPointerUp) {
  15810. _this.onPointerUp(evt, pickResult);
  15811. }
  15812. if (_this.onPointerObservable.hasObservers()) {
  15813. var type = PointerEventTypes.POINTERUP;
  15814. var pi = new PointerInfo(type, evt, pickResult);
  15815. _this.onPointerObservable.notifyObservers(pi, type);
  15816. }
  15817. _this._startingPointerTime = 0;
  15818. // Sprites
  15819. if (_this.spriteManagers.length > 0) {
  15820. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15821. if (pickResult.hit && pickResult.pickedSprite) {
  15822. if (pickResult.pickedSprite.actionManager) {
  15823. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15824. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  15825. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15826. }
  15827. }
  15828. }
  15829. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  15830. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  15831. }
  15832. }
  15833. };
  15834. this._onKeyDown = function (evt) {
  15835. if (_this.actionManager) {
  15836. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15837. }
  15838. };
  15839. this._onKeyUp = function (evt) {
  15840. if (_this.actionManager) {
  15841. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15842. }
  15843. };
  15844. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15845. var canvas = this._engine.getRenderingCanvas();
  15846. if (attachMove) {
  15847. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15848. // Wheel
  15849. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15850. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15851. }
  15852. if (attachDown) {
  15853. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15854. }
  15855. if (attachUp) {
  15856. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15857. }
  15858. canvas.tabIndex = 1;
  15859. canvas.addEventListener("keydown", this._onKeyDown, false);
  15860. canvas.addEventListener("keyup", this._onKeyUp, false);
  15861. };
  15862. Scene.prototype.detachControl = function () {
  15863. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15864. var canvas = this._engine.getRenderingCanvas();
  15865. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15866. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15867. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15868. // Wheel
  15869. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15870. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15871. canvas.removeEventListener("keydown", this._onKeyDown);
  15872. canvas.removeEventListener("keyup", this._onKeyUp);
  15873. };
  15874. // Ready
  15875. Scene.prototype.isReady = function () {
  15876. if (this._pendingData.length > 0) {
  15877. return false;
  15878. }
  15879. var index;
  15880. for (index = 0; index < this._geometries.length; index++) {
  15881. var geometry = this._geometries[index];
  15882. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15883. return false;
  15884. }
  15885. }
  15886. for (index = 0; index < this.meshes.length; index++) {
  15887. var mesh = this.meshes[index];
  15888. if (!mesh.isReady()) {
  15889. return false;
  15890. }
  15891. var mat = mesh.material;
  15892. if (mat) {
  15893. if (!mat.isReady(mesh)) {
  15894. return false;
  15895. }
  15896. }
  15897. }
  15898. return true;
  15899. };
  15900. Scene.prototype.resetCachedMaterial = function () {
  15901. this._cachedMaterial = null;
  15902. };
  15903. Scene.prototype.registerBeforeRender = function (func) {
  15904. this.onBeforeRenderObservable.add(func);
  15905. };
  15906. Scene.prototype.unregisterBeforeRender = function (func) {
  15907. this.onBeforeRenderObservable.removeCallback(func);
  15908. };
  15909. Scene.prototype.registerAfterRender = function (func) {
  15910. this.onAfterRenderObservable.add(func);
  15911. };
  15912. Scene.prototype.unregisterAfterRender = function (func) {
  15913. this.onAfterRenderObservable.removeCallback(func);
  15914. };
  15915. Scene.prototype._addPendingData = function (data) {
  15916. this._pendingData.push(data);
  15917. };
  15918. Scene.prototype._removePendingData = function (data) {
  15919. var index = this._pendingData.indexOf(data);
  15920. if (index !== -1) {
  15921. this._pendingData.splice(index, 1);
  15922. }
  15923. };
  15924. Scene.prototype.getWaitingItemsCount = function () {
  15925. return this._pendingData.length;
  15926. };
  15927. /**
  15928. * Registers a function to be executed when the scene is ready.
  15929. * @param {Function} func - the function to be executed.
  15930. */
  15931. Scene.prototype.executeWhenReady = function (func) {
  15932. var _this = this;
  15933. this.onReadyObservable.add(func);
  15934. if (this._executeWhenReadyTimeoutId !== -1) {
  15935. return;
  15936. }
  15937. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15938. _this._checkIsReady();
  15939. }, 150);
  15940. };
  15941. Scene.prototype._checkIsReady = function () {
  15942. var _this = this;
  15943. if (this.isReady()) {
  15944. this.onReadyObservable.notifyObservers(this);
  15945. this.onReadyObservable.clear();
  15946. this._executeWhenReadyTimeoutId = -1;
  15947. return;
  15948. }
  15949. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15950. _this._checkIsReady();
  15951. }, 150);
  15952. };
  15953. // Animations
  15954. /**
  15955. * Will start the animation sequence of a given target
  15956. * @param target - the target
  15957. * @param {number} from - from which frame should animation start
  15958. * @param {number} to - till which frame should animation run.
  15959. * @param {boolean} [loop] - should the animation loop
  15960. * @param {number} [speedRatio] - the speed in which to run the animation
  15961. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15962. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15963. * @return {BABYLON.Animatable} the animatable object created for this animation
  15964. * @see BABYLON.Animatable
  15965. * @see http://doc.babylonjs.com/page.php?p=22081
  15966. */
  15967. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15968. if (speedRatio === void 0) { speedRatio = 1.0; }
  15969. this.stopAnimation(target);
  15970. if (!animatable) {
  15971. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15972. }
  15973. // Local animations
  15974. if (target.animations) {
  15975. animatable.appendAnimations(target, target.animations);
  15976. }
  15977. // Children animations
  15978. if (target.getAnimatables) {
  15979. var animatables = target.getAnimatables();
  15980. for (var index = 0; index < animatables.length; index++) {
  15981. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15982. }
  15983. }
  15984. animatable.reset();
  15985. return animatable;
  15986. };
  15987. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15988. if (speedRatio === undefined) {
  15989. speedRatio = 1.0;
  15990. }
  15991. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15992. return animatable;
  15993. };
  15994. Scene.prototype.getAnimatableByTarget = function (target) {
  15995. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15996. if (this._activeAnimatables[index].target === target) {
  15997. return this._activeAnimatables[index];
  15998. }
  15999. }
  16000. return null;
  16001. };
  16002. Object.defineProperty(Scene.prototype, "Animatables", {
  16003. get: function () {
  16004. return this._activeAnimatables;
  16005. },
  16006. enumerable: true,
  16007. configurable: true
  16008. });
  16009. /**
  16010. * Will stop the animation of the given target
  16011. * @param target - the target
  16012. * @see beginAnimation
  16013. */
  16014. Scene.prototype.stopAnimation = function (target) {
  16015. var animatable = this.getAnimatableByTarget(target);
  16016. if (animatable) {
  16017. animatable.stop();
  16018. }
  16019. };
  16020. Scene.prototype._animate = function () {
  16021. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16022. return;
  16023. }
  16024. if (!this._animationStartDate) {
  16025. if (this._pendingData.length > 0) {
  16026. return;
  16027. }
  16028. this._animationStartDate = BABYLON.Tools.Now;
  16029. }
  16030. // Getting time
  16031. var now = BABYLON.Tools.Now;
  16032. var delay = now - this._animationStartDate;
  16033. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16034. this._activeAnimatables[index]._animate(delay);
  16035. }
  16036. };
  16037. // Matrix
  16038. Scene.prototype.getViewMatrix = function () {
  16039. return this._viewMatrix;
  16040. };
  16041. Scene.prototype.getProjectionMatrix = function () {
  16042. return this._projectionMatrix;
  16043. };
  16044. Scene.prototype.getTransformMatrix = function () {
  16045. return this._transformMatrix;
  16046. };
  16047. Scene.prototype.setTransformMatrix = function (view, projection) {
  16048. this._viewMatrix = view;
  16049. this._projectionMatrix = projection;
  16050. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16051. // Update frustum
  16052. if (!this._frustumPlanes) {
  16053. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16054. }
  16055. else {
  16056. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16057. }
  16058. };
  16059. // Methods
  16060. Scene.prototype.addMesh = function (newMesh) {
  16061. newMesh.uniqueId = this._uniqueIdCounter++;
  16062. var position = this.meshes.push(newMesh);
  16063. //notify the collision coordinator
  16064. this.collisionCoordinator.onMeshAdded(newMesh);
  16065. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16066. };
  16067. Scene.prototype.removeMesh = function (toRemove) {
  16068. var index = this.meshes.indexOf(toRemove);
  16069. if (index !== -1) {
  16070. // Remove from the scene if mesh found
  16071. this.meshes.splice(index, 1);
  16072. }
  16073. //notify the collision coordinator
  16074. this.collisionCoordinator.onMeshRemoved(toRemove);
  16075. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16076. return index;
  16077. };
  16078. Scene.prototype.removeSkeleton = function (toRemove) {
  16079. var index = this.skeletons.indexOf(toRemove);
  16080. if (index !== -1) {
  16081. // Remove from the scene if mesh found
  16082. this.skeletons.splice(index, 1);
  16083. }
  16084. return index;
  16085. };
  16086. Scene.prototype.removeLight = function (toRemove) {
  16087. var index = this.lights.indexOf(toRemove);
  16088. if (index !== -1) {
  16089. // Remove from the scene if mesh found
  16090. this.lights.splice(index, 1);
  16091. }
  16092. this.onLightRemovedObservable.notifyObservers(toRemove);
  16093. return index;
  16094. };
  16095. Scene.prototype.removeCamera = function (toRemove) {
  16096. var index = this.cameras.indexOf(toRemove);
  16097. if (index !== -1) {
  16098. // Remove from the scene if mesh found
  16099. this.cameras.splice(index, 1);
  16100. }
  16101. // Remove from activeCameras
  16102. var index2 = this.activeCameras.indexOf(toRemove);
  16103. if (index2 !== -1) {
  16104. // Remove from the scene if mesh found
  16105. this.activeCameras.splice(index2, 1);
  16106. }
  16107. // Reset the activeCamera
  16108. if (this.activeCamera === toRemove) {
  16109. if (this.cameras.length > 0) {
  16110. this.activeCamera = this.cameras[0];
  16111. }
  16112. else {
  16113. this.activeCamera = null;
  16114. }
  16115. }
  16116. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16117. return index;
  16118. };
  16119. Scene.prototype.addLight = function (newLight) {
  16120. newLight.uniqueId = this._uniqueIdCounter++;
  16121. var position = this.lights.push(newLight);
  16122. this.onNewLightAddedObservable.notifyObservers(newLight);
  16123. };
  16124. Scene.prototype.addCamera = function (newCamera) {
  16125. newCamera.uniqueId = this._uniqueIdCounter++;
  16126. var position = this.cameras.push(newCamera);
  16127. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16128. };
  16129. /**
  16130. * Switch active camera
  16131. * @param {Camera} newCamera - new active camera
  16132. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16133. */
  16134. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16135. if (attachControl === void 0) { attachControl = true; }
  16136. var canvas = this._engine.getRenderingCanvas();
  16137. this.activeCamera.detachControl(canvas);
  16138. this.activeCamera = newCamera;
  16139. if (attachControl) {
  16140. newCamera.attachControl(canvas);
  16141. }
  16142. };
  16143. /**
  16144. * sets the active camera of the scene using its ID
  16145. * @param {string} id - the camera's ID
  16146. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16147. * @see activeCamera
  16148. */
  16149. Scene.prototype.setActiveCameraByID = function (id) {
  16150. var camera = this.getCameraByID(id);
  16151. if (camera) {
  16152. this.activeCamera = camera;
  16153. return camera;
  16154. }
  16155. return null;
  16156. };
  16157. /**
  16158. * sets the active camera of the scene using its name
  16159. * @param {string} name - the camera's name
  16160. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16161. * @see activeCamera
  16162. */
  16163. Scene.prototype.setActiveCameraByName = function (name) {
  16164. var camera = this.getCameraByName(name);
  16165. if (camera) {
  16166. this.activeCamera = camera;
  16167. return camera;
  16168. }
  16169. return null;
  16170. };
  16171. /**
  16172. * get a material using its id
  16173. * @param {string} the material's ID
  16174. * @return {BABYLON.Material|null} the material or null if none found.
  16175. */
  16176. Scene.prototype.getMaterialByID = function (id) {
  16177. for (var index = 0; index < this.materials.length; index++) {
  16178. if (this.materials[index].id === id) {
  16179. return this.materials[index];
  16180. }
  16181. }
  16182. return null;
  16183. };
  16184. /**
  16185. * get a material using its name
  16186. * @param {string} the material's name
  16187. * @return {BABYLON.Material|null} the material or null if none found.
  16188. */
  16189. Scene.prototype.getMaterialByName = function (name) {
  16190. for (var index = 0; index < this.materials.length; index++) {
  16191. if (this.materials[index].name === name) {
  16192. return this.materials[index];
  16193. }
  16194. }
  16195. return null;
  16196. };
  16197. Scene.prototype.getLensFlareSystemByName = function (name) {
  16198. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16199. if (this.lensFlareSystems[index].name === name) {
  16200. return this.lensFlareSystems[index];
  16201. }
  16202. }
  16203. return null;
  16204. };
  16205. Scene.prototype.getLensFlareSystemByID = function (id) {
  16206. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16207. if (this.lensFlareSystems[index].id === id) {
  16208. return this.lensFlareSystems[index];
  16209. }
  16210. }
  16211. return null;
  16212. };
  16213. Scene.prototype.getCameraByID = function (id) {
  16214. for (var index = 0; index < this.cameras.length; index++) {
  16215. if (this.cameras[index].id === id) {
  16216. return this.cameras[index];
  16217. }
  16218. }
  16219. return null;
  16220. };
  16221. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16222. for (var index = 0; index < this.cameras.length; index++) {
  16223. if (this.cameras[index].uniqueId === uniqueId) {
  16224. return this.cameras[index];
  16225. }
  16226. }
  16227. return null;
  16228. };
  16229. /**
  16230. * get a camera using its name
  16231. * @param {string} the camera's name
  16232. * @return {BABYLON.Camera|null} the camera or null if none found.
  16233. */
  16234. Scene.prototype.getCameraByName = function (name) {
  16235. for (var index = 0; index < this.cameras.length; index++) {
  16236. if (this.cameras[index].name === name) {
  16237. return this.cameras[index];
  16238. }
  16239. }
  16240. return null;
  16241. };
  16242. /**
  16243. * get a bone using its id
  16244. * @param {string} the bone's id
  16245. * @return {BABYLON.Bone|null} the bone or null if not found
  16246. */
  16247. Scene.prototype.getBoneByID = function (id) {
  16248. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16249. var skeleton = this.skeletons[skeletonIndex];
  16250. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16251. if (skeleton.bones[boneIndex].id === id) {
  16252. return skeleton.bones[boneIndex];
  16253. }
  16254. }
  16255. }
  16256. return null;
  16257. };
  16258. /**
  16259. * get a bone using its id
  16260. * @param {string} the bone's name
  16261. * @return {BABYLON.Bone|null} the bone or null if not found
  16262. */
  16263. Scene.prototype.getBoneByName = function (name) {
  16264. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16265. var skeleton = this.skeletons[skeletonIndex];
  16266. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16267. if (skeleton.bones[boneIndex].name === name) {
  16268. return skeleton.bones[boneIndex];
  16269. }
  16270. }
  16271. }
  16272. return null;
  16273. };
  16274. /**
  16275. * get a light node using its name
  16276. * @param {string} the light's name
  16277. * @return {BABYLON.Light|null} the light or null if none found.
  16278. */
  16279. Scene.prototype.getLightByName = function (name) {
  16280. for (var index = 0; index < this.lights.length; index++) {
  16281. if (this.lights[index].name === name) {
  16282. return this.lights[index];
  16283. }
  16284. }
  16285. return null;
  16286. };
  16287. /**
  16288. * get a light node using its ID
  16289. * @param {string} the light's id
  16290. * @return {BABYLON.Light|null} the light or null if none found.
  16291. */
  16292. Scene.prototype.getLightByID = function (id) {
  16293. for (var index = 0; index < this.lights.length; index++) {
  16294. if (this.lights[index].id === id) {
  16295. return this.lights[index];
  16296. }
  16297. }
  16298. return null;
  16299. };
  16300. /**
  16301. * get a light node using its scene-generated unique ID
  16302. * @param {number} the light's unique id
  16303. * @return {BABYLON.Light|null} the light or null if none found.
  16304. */
  16305. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16306. for (var index = 0; index < this.lights.length; index++) {
  16307. if (this.lights[index].uniqueId === uniqueId) {
  16308. return this.lights[index];
  16309. }
  16310. }
  16311. return null;
  16312. };
  16313. /**
  16314. * get a particle system by id
  16315. * @param id {number} the particle system id
  16316. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16317. */
  16318. Scene.prototype.getParticleSystemByID = function (id) {
  16319. for (var index = 0; index < this.particleSystems.length; index++) {
  16320. if (this.particleSystems[index].id === id) {
  16321. return this.particleSystems[index];
  16322. }
  16323. }
  16324. return null;
  16325. };
  16326. /**
  16327. * get a geometry using its ID
  16328. * @param {string} the geometry's id
  16329. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16330. */
  16331. Scene.prototype.getGeometryByID = function (id) {
  16332. for (var index = 0; index < this._geometries.length; index++) {
  16333. if (this._geometries[index].id === id) {
  16334. return this._geometries[index];
  16335. }
  16336. }
  16337. return null;
  16338. };
  16339. /**
  16340. * add a new geometry to this scene.
  16341. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16342. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16343. * @return {boolean} was the geometry added or not
  16344. */
  16345. Scene.prototype.pushGeometry = function (geometry, force) {
  16346. if (!force && this.getGeometryByID(geometry.id)) {
  16347. return false;
  16348. }
  16349. this._geometries.push(geometry);
  16350. //notify the collision coordinator
  16351. this.collisionCoordinator.onGeometryAdded(geometry);
  16352. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16353. return true;
  16354. };
  16355. /**
  16356. * Removes an existing geometry
  16357. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16358. * @return {boolean} was the geometry removed or not
  16359. */
  16360. Scene.prototype.removeGeometry = function (geometry) {
  16361. var index = this._geometries.indexOf(geometry);
  16362. if (index > -1) {
  16363. this._geometries.splice(index, 1);
  16364. //notify the collision coordinator
  16365. this.collisionCoordinator.onGeometryDeleted(geometry);
  16366. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16367. return true;
  16368. }
  16369. return false;
  16370. };
  16371. Scene.prototype.getGeometries = function () {
  16372. return this._geometries;
  16373. };
  16374. /**
  16375. * Get the first added mesh found of a given ID
  16376. * @param {string} id - the id to search for
  16377. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16378. */
  16379. Scene.prototype.getMeshByID = function (id) {
  16380. for (var index = 0; index < this.meshes.length; index++) {
  16381. if (this.meshes[index].id === id) {
  16382. return this.meshes[index];
  16383. }
  16384. }
  16385. return null;
  16386. };
  16387. Scene.prototype.getMeshesByID = function (id) {
  16388. return this.meshes.filter(function (m) {
  16389. return m.id === id;
  16390. });
  16391. };
  16392. /**
  16393. * Get a mesh with its auto-generated unique id
  16394. * @param {number} uniqueId - the unique id to search for
  16395. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16396. */
  16397. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16398. for (var index = 0; index < this.meshes.length; index++) {
  16399. if (this.meshes[index].uniqueId === uniqueId) {
  16400. return this.meshes[index];
  16401. }
  16402. }
  16403. return null;
  16404. };
  16405. /**
  16406. * Get a the last added mesh found of a given ID
  16407. * @param {string} id - the id to search for
  16408. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16409. */
  16410. Scene.prototype.getLastMeshByID = function (id) {
  16411. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16412. if (this.meshes[index].id === id) {
  16413. return this.meshes[index];
  16414. }
  16415. }
  16416. return null;
  16417. };
  16418. /**
  16419. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16420. * @param {string} id - the id to search for
  16421. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16422. */
  16423. Scene.prototype.getLastEntryByID = function (id) {
  16424. var index;
  16425. for (index = this.meshes.length - 1; index >= 0; index--) {
  16426. if (this.meshes[index].id === id) {
  16427. return this.meshes[index];
  16428. }
  16429. }
  16430. for (index = this.cameras.length - 1; index >= 0; index--) {
  16431. if (this.cameras[index].id === id) {
  16432. return this.cameras[index];
  16433. }
  16434. }
  16435. for (index = this.lights.length - 1; index >= 0; index--) {
  16436. if (this.lights[index].id === id) {
  16437. return this.lights[index];
  16438. }
  16439. }
  16440. return null;
  16441. };
  16442. Scene.prototype.getNodeByID = function (id) {
  16443. var mesh = this.getMeshByID(id);
  16444. if (mesh) {
  16445. return mesh;
  16446. }
  16447. var light = this.getLightByID(id);
  16448. if (light) {
  16449. return light;
  16450. }
  16451. var camera = this.getCameraByID(id);
  16452. if (camera) {
  16453. return camera;
  16454. }
  16455. var bone = this.getBoneByID(id);
  16456. return bone;
  16457. };
  16458. Scene.prototype.getNodeByName = function (name) {
  16459. var mesh = this.getMeshByName(name);
  16460. if (mesh) {
  16461. return mesh;
  16462. }
  16463. var light = this.getLightByName(name);
  16464. if (light) {
  16465. return light;
  16466. }
  16467. var camera = this.getCameraByName(name);
  16468. if (camera) {
  16469. return camera;
  16470. }
  16471. var bone = this.getBoneByName(name);
  16472. return bone;
  16473. };
  16474. Scene.prototype.getMeshByName = function (name) {
  16475. for (var index = 0; index < this.meshes.length; index++) {
  16476. if (this.meshes[index].name === name) {
  16477. return this.meshes[index];
  16478. }
  16479. }
  16480. return null;
  16481. };
  16482. Scene.prototype.getSoundByName = function (name) {
  16483. var index;
  16484. if (BABYLON.AudioEngine) {
  16485. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16486. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16487. return this.mainSoundTrack.soundCollection[index];
  16488. }
  16489. }
  16490. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16491. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16492. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16493. return this.soundTracks[sdIndex].soundCollection[index];
  16494. }
  16495. }
  16496. }
  16497. }
  16498. return null;
  16499. };
  16500. Scene.prototype.getLastSkeletonByID = function (id) {
  16501. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16502. if (this.skeletons[index].id === id) {
  16503. return this.skeletons[index];
  16504. }
  16505. }
  16506. return null;
  16507. };
  16508. Scene.prototype.getSkeletonById = function (id) {
  16509. for (var index = 0; index < this.skeletons.length; index++) {
  16510. if (this.skeletons[index].id === id) {
  16511. return this.skeletons[index];
  16512. }
  16513. }
  16514. return null;
  16515. };
  16516. Scene.prototype.getSkeletonByName = function (name) {
  16517. for (var index = 0; index < this.skeletons.length; index++) {
  16518. if (this.skeletons[index].name === name) {
  16519. return this.skeletons[index];
  16520. }
  16521. }
  16522. return null;
  16523. };
  16524. Scene.prototype.isActiveMesh = function (mesh) {
  16525. return (this._activeMeshes.indexOf(mesh) !== -1);
  16526. };
  16527. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16528. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16529. var material = subMesh.getMaterial();
  16530. if (mesh.showSubMeshesBoundingBox) {
  16531. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  16532. }
  16533. if (material) {
  16534. // Render targets
  16535. if (material.getRenderTargetTextures) {
  16536. if (this._processedMaterials.indexOf(material) === -1) {
  16537. this._processedMaterials.push(material);
  16538. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16539. }
  16540. }
  16541. // Dispatch
  16542. this._activeIndices.addCount(subMesh.indexCount, false);
  16543. this._renderingManager.dispatch(subMesh);
  16544. }
  16545. }
  16546. };
  16547. Scene.prototype._isInIntermediateRendering = function () {
  16548. return this._intermediateRendering;
  16549. };
  16550. Scene.prototype._evaluateActiveMeshes = function () {
  16551. this.activeCamera._activeMeshes.reset();
  16552. this._activeMeshes.reset();
  16553. this._renderingManager.reset();
  16554. this._processedMaterials.reset();
  16555. this._activeParticleSystems.reset();
  16556. this._activeSkeletons.reset();
  16557. this._softwareSkinnedMeshes.reset();
  16558. this._boundingBoxRenderer.reset();
  16559. this._edgesRenderers.reset();
  16560. // Meshes
  16561. var meshes;
  16562. var len;
  16563. if (this._selectionOctree) {
  16564. var selection = this._selectionOctree.select(this._frustumPlanes);
  16565. meshes = selection.data;
  16566. len = selection.length;
  16567. }
  16568. else {
  16569. len = this.meshes.length;
  16570. meshes = this.meshes;
  16571. }
  16572. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16573. var mesh = meshes[meshIndex];
  16574. if (mesh.isBlocked) {
  16575. continue;
  16576. }
  16577. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16578. if (!mesh.isReady() || !mesh.isEnabled()) {
  16579. continue;
  16580. }
  16581. mesh.computeWorldMatrix();
  16582. // Intersections
  16583. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16584. this._meshesForIntersections.pushNoDuplicate(mesh);
  16585. }
  16586. // Switch to current LOD
  16587. var meshLOD = mesh.getLOD(this.activeCamera);
  16588. if (!meshLOD) {
  16589. continue;
  16590. }
  16591. mesh._preActivate();
  16592. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16593. this._activeMeshes.push(mesh);
  16594. this.activeCamera._activeMeshes.push(mesh);
  16595. mesh._activate(this._renderId);
  16596. this._activeMesh(mesh, meshLOD);
  16597. }
  16598. }
  16599. // Particle systems
  16600. this._particlesDuration.beginMonitoring();
  16601. var beforeParticlesDate = BABYLON.Tools.Now;
  16602. if (this.particlesEnabled) {
  16603. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16604. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16605. var particleSystem = this.particleSystems[particleIndex];
  16606. if (!particleSystem.isStarted()) {
  16607. continue;
  16608. }
  16609. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16610. this._activeParticleSystems.push(particleSystem);
  16611. particleSystem.animate();
  16612. }
  16613. }
  16614. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16615. }
  16616. this._particlesDuration.endMonitoring(false);
  16617. };
  16618. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16619. if (mesh.skeleton && this.skeletonsEnabled) {
  16620. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16621. mesh.skeleton.prepare();
  16622. }
  16623. if (!mesh.computeBonesUsingShaders) {
  16624. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16625. }
  16626. }
  16627. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16628. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16629. }
  16630. if (sourceMesh._edgesRenderer) {
  16631. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16632. }
  16633. if (mesh && mesh.subMeshes) {
  16634. // Submeshes Octrees
  16635. var len;
  16636. var subMeshes;
  16637. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16638. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16639. len = intersections.length;
  16640. subMeshes = intersections.data;
  16641. }
  16642. else {
  16643. subMeshes = mesh.subMeshes;
  16644. len = subMeshes.length;
  16645. }
  16646. for (var subIndex = 0; subIndex < len; subIndex++) {
  16647. var subMesh = subMeshes[subIndex];
  16648. this._evaluateSubMesh(subMesh, mesh);
  16649. }
  16650. }
  16651. };
  16652. Scene.prototype.updateTransformMatrix = function (force) {
  16653. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16654. };
  16655. Scene.prototype._renderForCamera = function (camera) {
  16656. var engine = this._engine;
  16657. var startTime = BABYLON.Tools.Now;
  16658. this.activeCamera = camera;
  16659. if (!this.activeCamera)
  16660. throw new Error("Active camera not set");
  16661. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16662. // Viewport
  16663. engine.setViewport(this.activeCamera.viewport);
  16664. // Camera
  16665. this.resetCachedMaterial();
  16666. this._renderId++;
  16667. this.updateTransformMatrix();
  16668. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16669. // Meshes
  16670. this._evaluateActiveMeshesDuration.beginMonitoring();
  16671. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16672. this._evaluateActiveMeshes();
  16673. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16674. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16675. // Software skinning
  16676. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16677. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16678. mesh.applySkeleton(mesh.skeleton);
  16679. }
  16680. // Render targets
  16681. this._renderTargetsDuration.beginMonitoring();
  16682. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16683. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16684. this._intermediateRendering = true;
  16685. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16686. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16687. var renderTarget = this._renderTargets.data[renderIndex];
  16688. if (renderTarget._shouldRender()) {
  16689. this._renderId++;
  16690. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16691. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16692. }
  16693. }
  16694. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16695. this._intermediateRendering = false;
  16696. this._renderId++;
  16697. engine.restoreDefaultFramebuffer(); // Restore back buffer
  16698. }
  16699. this._renderTargetsDuration.endMonitoring(false);
  16700. // Prepare Frame
  16701. this.postProcessManager._prepareFrame();
  16702. this._renderDuration.beginMonitoring();
  16703. // Backgrounds
  16704. var layerIndex;
  16705. var layer;
  16706. if (this.layers.length) {
  16707. engine.setDepthBuffer(false);
  16708. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16709. layer = this.layers[layerIndex];
  16710. if (layer.isBackground) {
  16711. layer.render();
  16712. }
  16713. }
  16714. engine.setDepthBuffer(true);
  16715. }
  16716. // Render
  16717. BABYLON.Tools.StartPerformanceCounter("Main render");
  16718. this._renderingManager.render(null, null, true, true);
  16719. BABYLON.Tools.EndPerformanceCounter("Main render");
  16720. // Bounding boxes
  16721. this._boundingBoxRenderer.render();
  16722. // Edges
  16723. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16724. this._edgesRenderers.data[edgesRendererIndex].render();
  16725. }
  16726. // Lens flares
  16727. if (this.lensFlaresEnabled) {
  16728. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16729. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16730. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16731. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16732. lensFlareSystem.render();
  16733. }
  16734. }
  16735. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16736. }
  16737. // Foregrounds
  16738. if (this.layers.length) {
  16739. engine.setDepthBuffer(false);
  16740. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16741. layer = this.layers[layerIndex];
  16742. if (!layer.isBackground) {
  16743. layer.render();
  16744. }
  16745. }
  16746. engine.setDepthBuffer(true);
  16747. }
  16748. this._renderDuration.endMonitoring(false);
  16749. // Finalize frame
  16750. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16751. // Update camera
  16752. this.activeCamera._updateFromScene();
  16753. // Reset some special arrays
  16754. this._renderTargets.reset();
  16755. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16756. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16757. };
  16758. Scene.prototype._processSubCameras = function (camera) {
  16759. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16760. this._renderForCamera(camera);
  16761. return;
  16762. }
  16763. // rig cameras
  16764. for (var index = 0; index < camera._rigCameras.length; index++) {
  16765. this._renderForCamera(camera._rigCameras[index]);
  16766. }
  16767. this.activeCamera = camera;
  16768. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16769. // Update camera
  16770. this.activeCamera._updateFromScene();
  16771. };
  16772. Scene.prototype._checkIntersections = function () {
  16773. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16774. var sourceMesh = this._meshesForIntersections.data[index];
  16775. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16776. var action = sourceMesh.actionManager.actions[actionIndex];
  16777. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16778. var parameters = action.getTriggerParameter();
  16779. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16780. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16781. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16782. if (areIntersecting && currentIntersectionInProgress === -1) {
  16783. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16784. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16785. sourceMesh._intersectionsInProgress.push(otherMesh);
  16786. }
  16787. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16788. sourceMesh._intersectionsInProgress.push(otherMesh);
  16789. }
  16790. }
  16791. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16792. //They intersected, and now they don't.
  16793. //is this trigger an exit trigger? execute an event.
  16794. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16795. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16796. }
  16797. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16798. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16799. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16800. }
  16801. }
  16802. }
  16803. }
  16804. }
  16805. };
  16806. Scene.prototype.render = function () {
  16807. this._lastFrameDuration.beginMonitoring();
  16808. this._particlesDuration.fetchNewFrame();
  16809. this._spritesDuration.fetchNewFrame();
  16810. this._activeParticles.fetchNewFrame();
  16811. this._renderDuration.fetchNewFrame();
  16812. this._renderTargetsDuration.fetchNewFrame();
  16813. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16814. this._totalVertices.fetchNewFrame();
  16815. this._activeIndices.fetchNewFrame();
  16816. this._activeBones.fetchNewFrame();
  16817. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16818. this._meshesForIntersections.reset();
  16819. this.resetCachedMaterial();
  16820. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16821. // Actions
  16822. if (this.actionManager) {
  16823. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16824. }
  16825. //Simplification Queue
  16826. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16827. this.simplificationQueue.executeNext();
  16828. }
  16829. // Animations
  16830. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16831. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16832. this._animate();
  16833. // Physics
  16834. if (this._physicsEngine) {
  16835. BABYLON.Tools.StartPerformanceCounter("Physics");
  16836. this._physicsEngine._step(deltaTime / 1000.0);
  16837. BABYLON.Tools.EndPerformanceCounter("Physics");
  16838. }
  16839. // Before render
  16840. this.onBeforeRenderObservable.notifyObservers(this);
  16841. // Customs render targets
  16842. this._renderTargetsDuration.beginMonitoring();
  16843. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16844. var engine = this.getEngine();
  16845. var currentActiveCamera = this.activeCamera;
  16846. if (this.renderTargetsEnabled) {
  16847. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16848. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16849. var renderTarget = this.customRenderTargets[customIndex];
  16850. if (renderTarget._shouldRender()) {
  16851. this._renderId++;
  16852. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16853. if (!this.activeCamera)
  16854. throw new Error("Active camera not set");
  16855. // Viewport
  16856. engine.setViewport(this.activeCamera.viewport);
  16857. // Camera
  16858. this.updateTransformMatrix();
  16859. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16860. }
  16861. }
  16862. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16863. this._renderId++;
  16864. }
  16865. if (this.customRenderTargets.length > 0) {
  16866. engine.restoreDefaultFramebuffer();
  16867. }
  16868. this._renderTargetsDuration.endMonitoring();
  16869. this.activeCamera = currentActiveCamera;
  16870. // Procedural textures
  16871. if (this.proceduralTexturesEnabled) {
  16872. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16873. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16874. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16875. if (proceduralTexture._shouldRender()) {
  16876. proceduralTexture.render();
  16877. }
  16878. }
  16879. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16880. }
  16881. // Clear
  16882. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  16883. // Shadows
  16884. if (this.shadowsEnabled) {
  16885. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16886. var light = this.lights[lightIndex];
  16887. var shadowGenerator = light.getShadowGenerator();
  16888. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16889. this._renderTargets.push(shadowGenerator.getShadowMap());
  16890. }
  16891. }
  16892. }
  16893. // Depth renderer
  16894. if (this._depthRenderer) {
  16895. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16896. }
  16897. // RenderPipeline
  16898. this.postProcessRenderPipelineManager.update();
  16899. // Multi-cameras?
  16900. if (this.activeCameras.length > 0) {
  16901. var currentRenderId = this._renderId;
  16902. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16903. this._renderId = currentRenderId;
  16904. if (cameraIndex > 0) {
  16905. this._engine.clear(0, false, true);
  16906. }
  16907. this._processSubCameras(this.activeCameras[cameraIndex]);
  16908. }
  16909. }
  16910. else {
  16911. if (!this.activeCamera) {
  16912. throw new Error("No camera defined");
  16913. }
  16914. this._processSubCameras(this.activeCamera);
  16915. }
  16916. // Intersection checks
  16917. this._checkIntersections();
  16918. // Update the audio listener attached to the camera
  16919. if (BABYLON.AudioEngine) {
  16920. this._updateAudioParameters();
  16921. }
  16922. // After render
  16923. if (this.afterRender) {
  16924. this.afterRender();
  16925. }
  16926. this.onAfterRenderObservable.notifyObservers(this);
  16927. // Cleaning
  16928. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16929. this._toBeDisposed.data[index].dispose();
  16930. this._toBeDisposed[index] = null;
  16931. }
  16932. this._toBeDisposed.reset();
  16933. if (this.dumpNextRenderTargets) {
  16934. this.dumpNextRenderTargets = false;
  16935. }
  16936. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16937. this._lastFrameDuration.endMonitoring();
  16938. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16939. this._totalLightsCounter.addCount(this.lights.length, true);
  16940. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16941. this._totalTexturesCounter.addCount(this.textures.length, true);
  16942. this._activeBones.addCount(0, true);
  16943. this._activeIndices.addCount(0, true);
  16944. this._activeParticles.addCount(0, true);
  16945. };
  16946. Scene.prototype._updateAudioParameters = function () {
  16947. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16948. return;
  16949. }
  16950. var listeningCamera;
  16951. var audioEngine = BABYLON.Engine.audioEngine;
  16952. if (this.activeCameras.length > 0) {
  16953. listeningCamera = this.activeCameras[0];
  16954. }
  16955. else {
  16956. listeningCamera = this.activeCamera;
  16957. }
  16958. if (listeningCamera && audioEngine.canUseWebAudio) {
  16959. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16960. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16961. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16962. cameraDirection.normalize();
  16963. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16964. var i;
  16965. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16966. var sound = this.mainSoundTrack.soundCollection[i];
  16967. if (sound.useCustomAttenuation) {
  16968. sound.updateDistanceFromListener();
  16969. }
  16970. }
  16971. for (i = 0; i < this.soundTracks.length; i++) {
  16972. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16973. sound = this.soundTracks[i].soundCollection[j];
  16974. if (sound.useCustomAttenuation) {
  16975. sound.updateDistanceFromListener();
  16976. }
  16977. }
  16978. }
  16979. }
  16980. };
  16981. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16982. // Audio
  16983. get: function () {
  16984. return this._audioEnabled;
  16985. },
  16986. set: function (value) {
  16987. this._audioEnabled = value;
  16988. if (BABYLON.AudioEngine) {
  16989. if (this._audioEnabled) {
  16990. this._enableAudio();
  16991. }
  16992. else {
  16993. this._disableAudio();
  16994. }
  16995. }
  16996. },
  16997. enumerable: true,
  16998. configurable: true
  16999. });
  17000. Scene.prototype._disableAudio = function () {
  17001. var i;
  17002. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17003. this.mainSoundTrack.soundCollection[i].pause();
  17004. }
  17005. for (i = 0; i < this.soundTracks.length; i++) {
  17006. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17007. this.soundTracks[i].soundCollection[j].pause();
  17008. }
  17009. }
  17010. };
  17011. Scene.prototype._enableAudio = function () {
  17012. var i;
  17013. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17014. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17015. this.mainSoundTrack.soundCollection[i].play();
  17016. }
  17017. }
  17018. for (i = 0; i < this.soundTracks.length; i++) {
  17019. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17020. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17021. this.soundTracks[i].soundCollection[j].play();
  17022. }
  17023. }
  17024. }
  17025. };
  17026. Object.defineProperty(Scene.prototype, "headphone", {
  17027. get: function () {
  17028. return this._headphone;
  17029. },
  17030. set: function (value) {
  17031. this._headphone = value;
  17032. if (BABYLON.AudioEngine) {
  17033. if (this._headphone) {
  17034. this._switchAudioModeForHeadphones();
  17035. }
  17036. else {
  17037. this._switchAudioModeForNormalSpeakers();
  17038. }
  17039. }
  17040. },
  17041. enumerable: true,
  17042. configurable: true
  17043. });
  17044. Scene.prototype._switchAudioModeForHeadphones = function () {
  17045. this.mainSoundTrack.switchPanningModelToHRTF();
  17046. for (var i = 0; i < this.soundTracks.length; i++) {
  17047. this.soundTracks[i].switchPanningModelToHRTF();
  17048. }
  17049. };
  17050. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17051. this.mainSoundTrack.switchPanningModelToEqualPower();
  17052. for (var i = 0; i < this.soundTracks.length; i++) {
  17053. this.soundTracks[i].switchPanningModelToEqualPower();
  17054. }
  17055. };
  17056. Scene.prototype.enableDepthRenderer = function () {
  17057. if (this._depthRenderer) {
  17058. return this._depthRenderer;
  17059. }
  17060. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17061. return this._depthRenderer;
  17062. };
  17063. Scene.prototype.disableDepthRenderer = function () {
  17064. if (!this._depthRenderer) {
  17065. return;
  17066. }
  17067. this._depthRenderer.dispose();
  17068. this._depthRenderer = null;
  17069. };
  17070. Scene.prototype.freezeMaterials = function () {
  17071. for (var i = 0; i < this.materials.length; i++) {
  17072. this.materials[i].freeze();
  17073. }
  17074. };
  17075. Scene.prototype.unfreezeMaterials = function () {
  17076. for (var i = 0; i < this.materials.length; i++) {
  17077. this.materials[i].unfreeze();
  17078. }
  17079. };
  17080. Scene.prototype.dispose = function () {
  17081. this.beforeRender = null;
  17082. this.afterRender = null;
  17083. this.skeletons = [];
  17084. this._boundingBoxRenderer.dispose();
  17085. if (this._depthRenderer) {
  17086. this._depthRenderer.dispose();
  17087. }
  17088. // Debug layer
  17089. if (this._debugLayer) {
  17090. this._debugLayer.hide();
  17091. }
  17092. // Events
  17093. this.onDisposeObservable.notifyObservers(this);
  17094. this.onDisposeObservable.clear();
  17095. this.onBeforeRenderObservable.clear();
  17096. this.onAfterRenderObservable.clear();
  17097. this.detachControl();
  17098. // Release sounds & sounds tracks
  17099. if (BABYLON.AudioEngine) {
  17100. this.disposeSounds();
  17101. }
  17102. // Detach cameras
  17103. var canvas = this._engine.getRenderingCanvas();
  17104. var index;
  17105. for (index = 0; index < this.cameras.length; index++) {
  17106. this.cameras[index].detachControl(canvas);
  17107. }
  17108. // Release lights
  17109. while (this.lights.length) {
  17110. this.lights[0].dispose();
  17111. }
  17112. // Release meshes
  17113. while (this.meshes.length) {
  17114. this.meshes[0].dispose(true);
  17115. }
  17116. // Release cameras
  17117. while (this.cameras.length) {
  17118. this.cameras[0].dispose();
  17119. }
  17120. // Release materials
  17121. while (this.materials.length) {
  17122. this.materials[0].dispose();
  17123. }
  17124. // Release particles
  17125. while (this.particleSystems.length) {
  17126. this.particleSystems[0].dispose();
  17127. }
  17128. // Release sprites
  17129. while (this.spriteManagers.length) {
  17130. this.spriteManagers[0].dispose();
  17131. }
  17132. // Release layers
  17133. while (this.layers.length) {
  17134. this.layers[0].dispose();
  17135. }
  17136. // Release textures
  17137. while (this.textures.length) {
  17138. this.textures[0].dispose();
  17139. }
  17140. // Post-processes
  17141. this.postProcessManager.dispose();
  17142. // Physics
  17143. if (this._physicsEngine) {
  17144. this.disablePhysicsEngine();
  17145. }
  17146. // Remove from engine
  17147. index = this._engine.scenes.indexOf(this);
  17148. if (index > -1) {
  17149. this._engine.scenes.splice(index, 1);
  17150. }
  17151. this._engine.wipeCaches();
  17152. };
  17153. // Release sounds & sounds tracks
  17154. Scene.prototype.disposeSounds = function () {
  17155. this.mainSoundTrack.dispose();
  17156. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17157. this.soundTracks[scIndex].dispose();
  17158. }
  17159. };
  17160. // Octrees
  17161. Scene.prototype.getWorldExtends = function () {
  17162. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17163. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17164. for (var index = 0; index < this.meshes.length; index++) {
  17165. var mesh = this.meshes[index];
  17166. mesh.computeWorldMatrix(true);
  17167. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17168. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17169. BABYLON.Tools.CheckExtends(minBox, min, max);
  17170. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17171. }
  17172. return {
  17173. min: min,
  17174. max: max
  17175. };
  17176. };
  17177. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17178. if (maxCapacity === void 0) { maxCapacity = 64; }
  17179. if (maxDepth === void 0) { maxDepth = 2; }
  17180. if (!this._selectionOctree) {
  17181. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17182. }
  17183. var worldExtends = this.getWorldExtends();
  17184. // Update octree
  17185. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17186. return this._selectionOctree;
  17187. };
  17188. // Picking
  17189. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17190. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17191. var engine = this._engine;
  17192. if (!camera) {
  17193. if (!this.activeCamera)
  17194. throw new Error("Active camera not set");
  17195. camera = this.activeCamera;
  17196. }
  17197. var cameraViewport = camera.viewport;
  17198. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17199. // Moving coordinates to local viewport world
  17200. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17201. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17202. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17203. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17204. };
  17205. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17206. var engine = this._engine;
  17207. if (!camera) {
  17208. if (!this.activeCamera)
  17209. throw new Error("Active camera not set");
  17210. camera = this.activeCamera;
  17211. }
  17212. var cameraViewport = camera.viewport;
  17213. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17214. var identity = BABYLON.Matrix.Identity();
  17215. // Moving coordinates to local viewport world
  17216. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17217. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17218. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17219. };
  17220. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17221. var pickingInfo = null;
  17222. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17223. var mesh = this.meshes[meshIndex];
  17224. if (predicate) {
  17225. if (!predicate(mesh)) {
  17226. continue;
  17227. }
  17228. }
  17229. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17230. continue;
  17231. }
  17232. var world = mesh.getWorldMatrix();
  17233. var ray = rayFunction(world);
  17234. var result = mesh.intersects(ray, fastCheck);
  17235. if (!result || !result.hit)
  17236. continue;
  17237. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17238. continue;
  17239. pickingInfo = result;
  17240. if (fastCheck) {
  17241. break;
  17242. }
  17243. }
  17244. return pickingInfo || new BABYLON.PickingInfo();
  17245. };
  17246. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17247. var pickingInfo = null;
  17248. camera = camera || this.activeCamera;
  17249. if (this.spriteManagers.length > 0) {
  17250. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17251. var spriteManager = this.spriteManagers[spriteIndex];
  17252. if (!spriteManager.isPickable) {
  17253. continue;
  17254. }
  17255. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17256. if (!result || !result.hit)
  17257. continue;
  17258. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17259. continue;
  17260. pickingInfo = result;
  17261. if (fastCheck) {
  17262. break;
  17263. }
  17264. }
  17265. }
  17266. return pickingInfo || new BABYLON.PickingInfo();
  17267. };
  17268. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17269. var _this = this;
  17270. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17271. /// <param name="x">X position on screen</param>
  17272. /// <param name="y">Y position on screen</param>
  17273. /// <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>
  17274. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17275. /// <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>
  17276. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17277. };
  17278. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17279. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17280. /// <param name="x">X position on screen</param>
  17281. /// <param name="y">Y position on screen</param>
  17282. /// <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>
  17283. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17284. /// <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>
  17285. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17286. };
  17287. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17288. var _this = this;
  17289. return this._internalPick(function (world) {
  17290. if (!_this._pickWithRayInverseMatrix) {
  17291. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17292. }
  17293. world.invertToRef(_this._pickWithRayInverseMatrix);
  17294. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17295. }, predicate, fastCheck);
  17296. };
  17297. Scene.prototype.setPointerOverMesh = function (mesh) {
  17298. if (this._pointerOverMesh === mesh) {
  17299. return;
  17300. }
  17301. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17302. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17303. }
  17304. this._pointerOverMesh = mesh;
  17305. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17306. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17307. }
  17308. };
  17309. Scene.prototype.getPointerOverMesh = function () {
  17310. return this._pointerOverMesh;
  17311. };
  17312. Scene.prototype.setPointerOverSprite = function (sprite) {
  17313. if (this._pointerOverSprite === sprite) {
  17314. return;
  17315. }
  17316. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17317. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17318. }
  17319. this._pointerOverSprite = sprite;
  17320. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17321. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17322. }
  17323. };
  17324. Scene.prototype.getPointerOverSprite = function () {
  17325. return this._pointerOverSprite;
  17326. };
  17327. // Physics
  17328. Scene.prototype.getPhysicsEngine = function () {
  17329. return this._physicsEngine;
  17330. };
  17331. /**
  17332. * Enables physics to the current scene
  17333. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17334. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17335. * @return {boolean} was the physics engine initialized
  17336. */
  17337. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17338. if (this._physicsEngine) {
  17339. return true;
  17340. }
  17341. try {
  17342. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17343. return true;
  17344. }
  17345. catch (e) {
  17346. BABYLON.Tools.Error(e.message);
  17347. return false;
  17348. }
  17349. };
  17350. Scene.prototype.disablePhysicsEngine = function () {
  17351. if (!this._physicsEngine) {
  17352. return;
  17353. }
  17354. this._physicsEngine.dispose();
  17355. this._physicsEngine = undefined;
  17356. };
  17357. Scene.prototype.isPhysicsEnabled = function () {
  17358. return this._physicsEngine !== undefined;
  17359. };
  17360. /**
  17361. *
  17362. * Sets the gravity of the physics engine (and NOT of the scene)
  17363. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17364. */
  17365. Scene.prototype.setGravity = function (gravity) {
  17366. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17367. if (!this._physicsEngine) {
  17368. return;
  17369. }
  17370. this._physicsEngine.setGravity(gravity);
  17371. };
  17372. /**
  17373. * Legacy support, using the new API
  17374. * @Deprecated
  17375. */
  17376. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17377. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17378. if (parts.parts) {
  17379. options = parts;
  17380. parts = parts.parts;
  17381. }
  17382. var mainMesh = parts[0].mesh;
  17383. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17384. for (var index = 1; index < parts.length; index++) {
  17385. var mesh = parts[index].mesh;
  17386. if (mesh.parent !== mainMesh) {
  17387. mesh.position = mesh.position.subtract(mainMesh.position);
  17388. mesh.parent = mainMesh;
  17389. }
  17390. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17391. }
  17392. mainMesh.physicsImpostor.forceUpdate();
  17393. };
  17394. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17395. var mesh = compound.parts[0].mesh;
  17396. mesh.physicsImpostor.dispose();
  17397. mesh.physicsImpostor = null;
  17398. };
  17399. // Misc.
  17400. Scene.prototype.createDefaultCameraOrLight = function () {
  17401. // Light
  17402. if (this.lights.length === 0) {
  17403. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17404. }
  17405. // Camera
  17406. if (!this.activeCamera) {
  17407. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17408. // Compute position
  17409. var worldExtends = this.getWorldExtends();
  17410. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17411. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17412. camera.setTarget(worldCenter);
  17413. this.activeCamera = camera;
  17414. }
  17415. };
  17416. // Tags
  17417. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17418. if (tagsQuery === undefined) {
  17419. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17420. return list;
  17421. }
  17422. var listByTags = [];
  17423. forEach = forEach || (function (item) { return; });
  17424. for (var i in list) {
  17425. var item = list[i];
  17426. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17427. listByTags.push(item);
  17428. forEach(item);
  17429. }
  17430. }
  17431. return listByTags;
  17432. };
  17433. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17434. return this._getByTags(this.meshes, tagsQuery, forEach);
  17435. };
  17436. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17437. return this._getByTags(this.cameras, tagsQuery, forEach);
  17438. };
  17439. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17440. return this._getByTags(this.lights, tagsQuery, forEach);
  17441. };
  17442. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17443. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17444. };
  17445. // Statics
  17446. Scene._FOGMODE_NONE = 0;
  17447. Scene._FOGMODE_EXP = 1;
  17448. Scene._FOGMODE_EXP2 = 2;
  17449. Scene._FOGMODE_LINEAR = 3;
  17450. Scene.MinDeltaTime = 1.0;
  17451. Scene.MaxDeltaTime = 1000.0;
  17452. return Scene;
  17453. })();
  17454. BABYLON.Scene = Scene;
  17455. })(BABYLON || (BABYLON = {}));
  17456. var BABYLON;
  17457. (function (BABYLON) {
  17458. var Buffer = (function () {
  17459. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17460. if (engine instanceof BABYLON.Mesh) {
  17461. this._engine = engine.getScene().getEngine();
  17462. }
  17463. else {
  17464. this._engine = engine;
  17465. }
  17466. this._updatable = updatable;
  17467. this._data = data;
  17468. this._strideSize = stride;
  17469. if (!postponeInternalCreation) {
  17470. this.create();
  17471. }
  17472. this._instanced = instanced;
  17473. }
  17474. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17475. // a lot of these parameters are ignored as they are overriden by the buffer
  17476. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17477. };
  17478. // Properties
  17479. Buffer.prototype.isUpdatable = function () {
  17480. return this._updatable;
  17481. };
  17482. Buffer.prototype.getData = function () {
  17483. return this._data;
  17484. };
  17485. Buffer.prototype.getBuffer = function () {
  17486. return this._buffer;
  17487. };
  17488. Buffer.prototype.getStrideSize = function () {
  17489. return this._strideSize;
  17490. };
  17491. Buffer.prototype.getIsInstanced = function () {
  17492. return this._instanced;
  17493. };
  17494. // Methods
  17495. Buffer.prototype.create = function (data) {
  17496. if (!data && this._buffer) {
  17497. return; // nothing to do
  17498. }
  17499. data = data || this._data;
  17500. if (!this._buffer) {
  17501. if (this._updatable) {
  17502. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17503. this._data = data;
  17504. }
  17505. else {
  17506. this._buffer = this._engine.createVertexBuffer(data);
  17507. }
  17508. }
  17509. else if (this._updatable) {
  17510. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17511. this._data = data;
  17512. }
  17513. };
  17514. Buffer.prototype.update = function (data) {
  17515. this.create(data);
  17516. };
  17517. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17518. if (!this._buffer) {
  17519. return;
  17520. }
  17521. if (this._updatable) {
  17522. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17523. this._data = null;
  17524. }
  17525. };
  17526. Buffer.prototype.dispose = function () {
  17527. if (!this._buffer) {
  17528. return;
  17529. }
  17530. if (this._engine._releaseBuffer(this._buffer)) {
  17531. this._buffer = null;
  17532. }
  17533. };
  17534. return Buffer;
  17535. })();
  17536. BABYLON.Buffer = Buffer;
  17537. })(BABYLON || (BABYLON = {}));
  17538. var BABYLON;
  17539. (function (BABYLON) {
  17540. var VertexBuffer = (function () {
  17541. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17542. if (!stride) {
  17543. // Deduce stride from kind
  17544. switch (kind) {
  17545. case VertexBuffer.PositionKind:
  17546. stride = 3;
  17547. break;
  17548. case VertexBuffer.NormalKind:
  17549. stride = 3;
  17550. break;
  17551. case VertexBuffer.UVKind:
  17552. case VertexBuffer.UV2Kind:
  17553. case VertexBuffer.UV3Kind:
  17554. case VertexBuffer.UV4Kind:
  17555. case VertexBuffer.UV5Kind:
  17556. case VertexBuffer.UV6Kind:
  17557. stride = 2;
  17558. break;
  17559. case VertexBuffer.ColorKind:
  17560. stride = 4;
  17561. break;
  17562. case VertexBuffer.MatricesIndicesKind:
  17563. case VertexBuffer.MatricesIndicesExtraKind:
  17564. stride = 4;
  17565. break;
  17566. case VertexBuffer.MatricesWeightsKind:
  17567. case VertexBuffer.MatricesWeightsExtraKind:
  17568. stride = 4;
  17569. break;
  17570. }
  17571. }
  17572. if (data instanceof BABYLON.Buffer) {
  17573. if (!stride) {
  17574. stride = data.getStrideSize();
  17575. }
  17576. this._buffer = data;
  17577. this._ownsBuffer = false;
  17578. }
  17579. else {
  17580. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17581. this._ownsBuffer = true;
  17582. }
  17583. this._stride = stride;
  17584. this._offset = offset ? offset : 0;
  17585. this._size = size ? size : stride;
  17586. this._kind = kind;
  17587. }
  17588. VertexBuffer.prototype.getKind = function () {
  17589. return this._kind;
  17590. };
  17591. // Properties
  17592. VertexBuffer.prototype.isUpdatable = function () {
  17593. return this._buffer.isUpdatable();
  17594. };
  17595. VertexBuffer.prototype.getData = function () {
  17596. return this._buffer.getData();
  17597. };
  17598. VertexBuffer.prototype.getBuffer = function () {
  17599. return this._buffer.getBuffer();
  17600. };
  17601. VertexBuffer.prototype.getStrideSize = function () {
  17602. return this._stride;
  17603. };
  17604. VertexBuffer.prototype.getOffset = function () {
  17605. return this._offset;
  17606. };
  17607. VertexBuffer.prototype.getSize = function () {
  17608. return this._size;
  17609. };
  17610. VertexBuffer.prototype.getIsInstanced = function () {
  17611. return this._buffer.getIsInstanced();
  17612. };
  17613. // Methods
  17614. VertexBuffer.prototype.create = function (data) {
  17615. return this._buffer.create(data);
  17616. };
  17617. VertexBuffer.prototype.update = function (data) {
  17618. return this._buffer.update(data);
  17619. };
  17620. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17621. return this._buffer.updateDirectly(data, offset);
  17622. };
  17623. VertexBuffer.prototype.dispose = function () {
  17624. if (this._ownsBuffer) {
  17625. this._buffer.dispose();
  17626. }
  17627. };
  17628. Object.defineProperty(VertexBuffer, "PositionKind", {
  17629. get: function () {
  17630. return VertexBuffer._PositionKind;
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(VertexBuffer, "NormalKind", {
  17636. get: function () {
  17637. return VertexBuffer._NormalKind;
  17638. },
  17639. enumerable: true,
  17640. configurable: true
  17641. });
  17642. Object.defineProperty(VertexBuffer, "UVKind", {
  17643. get: function () {
  17644. return VertexBuffer._UVKind;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17650. get: function () {
  17651. return VertexBuffer._UV2Kind;
  17652. },
  17653. enumerable: true,
  17654. configurable: true
  17655. });
  17656. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17657. get: function () {
  17658. return VertexBuffer._UV3Kind;
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17664. get: function () {
  17665. return VertexBuffer._UV4Kind;
  17666. },
  17667. enumerable: true,
  17668. configurable: true
  17669. });
  17670. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17671. get: function () {
  17672. return VertexBuffer._UV5Kind;
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17678. get: function () {
  17679. return VertexBuffer._UV6Kind;
  17680. },
  17681. enumerable: true,
  17682. configurable: true
  17683. });
  17684. Object.defineProperty(VertexBuffer, "ColorKind", {
  17685. get: function () {
  17686. return VertexBuffer._ColorKind;
  17687. },
  17688. enumerable: true,
  17689. configurable: true
  17690. });
  17691. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17692. get: function () {
  17693. return VertexBuffer._MatricesIndicesKind;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17699. get: function () {
  17700. return VertexBuffer._MatricesWeightsKind;
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17706. get: function () {
  17707. return VertexBuffer._MatricesIndicesExtraKind;
  17708. },
  17709. enumerable: true,
  17710. configurable: true
  17711. });
  17712. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17713. get: function () {
  17714. return VertexBuffer._MatricesWeightsExtraKind;
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. // Enums
  17720. VertexBuffer._PositionKind = "position";
  17721. VertexBuffer._NormalKind = "normal";
  17722. VertexBuffer._UVKind = "uv";
  17723. VertexBuffer._UV2Kind = "uv2";
  17724. VertexBuffer._UV3Kind = "uv3";
  17725. VertexBuffer._UV4Kind = "uv4";
  17726. VertexBuffer._UV5Kind = "uv5";
  17727. VertexBuffer._UV6Kind = "uv6";
  17728. VertexBuffer._ColorKind = "color";
  17729. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17730. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17731. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17732. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17733. return VertexBuffer;
  17734. })();
  17735. BABYLON.VertexBuffer = VertexBuffer;
  17736. })(BABYLON || (BABYLON = {}));
  17737. var BABYLON;
  17738. (function (BABYLON) {
  17739. /**
  17740. * Creates an instance based on a source mesh.
  17741. */
  17742. var InstancedMesh = (function (_super) {
  17743. __extends(InstancedMesh, _super);
  17744. function InstancedMesh(name, source) {
  17745. _super.call(this, name, source.getScene());
  17746. source.instances.push(this);
  17747. this._sourceMesh = source;
  17748. this.position.copyFrom(source.position);
  17749. this.rotation.copyFrom(source.rotation);
  17750. this.scaling.copyFrom(source.scaling);
  17751. if (source.rotationQuaternion) {
  17752. this.rotationQuaternion = source.rotationQuaternion.clone();
  17753. }
  17754. this.infiniteDistance = source.infiniteDistance;
  17755. this.setPivotMatrix(source.getPivotMatrix());
  17756. this.refreshBoundingInfo();
  17757. this._syncSubMeshes();
  17758. }
  17759. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  17760. // Methods
  17761. get: function () {
  17762. return this._sourceMesh.receiveShadows;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(InstancedMesh.prototype, "material", {
  17768. get: function () {
  17769. return this._sourceMesh.material;
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  17775. get: function () {
  17776. return this._sourceMesh.visibility;
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  17782. get: function () {
  17783. return this._sourceMesh.skeleton;
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  17789. get: function () {
  17790. return this._sourceMesh.renderingGroupId;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. InstancedMesh.prototype.getTotalVertices = function () {
  17796. return this._sourceMesh.getTotalVertices();
  17797. };
  17798. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  17799. get: function () {
  17800. return this._sourceMesh;
  17801. },
  17802. enumerable: true,
  17803. configurable: true
  17804. });
  17805. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17806. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  17807. };
  17808. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  17809. return this._sourceMesh.isVerticesDataPresent(kind);
  17810. };
  17811. InstancedMesh.prototype.getIndices = function () {
  17812. return this._sourceMesh.getIndices();
  17813. };
  17814. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  17815. get: function () {
  17816. return this._sourceMesh._positions;
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. InstancedMesh.prototype.refreshBoundingInfo = function () {
  17822. var meshBB = this._sourceMesh.getBoundingInfo();
  17823. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  17824. this._updateBoundingInfo();
  17825. };
  17826. InstancedMesh.prototype._preActivate = function () {
  17827. if (this._currentLOD) {
  17828. this._currentLOD._preActivate();
  17829. }
  17830. };
  17831. InstancedMesh.prototype._activate = function (renderId) {
  17832. if (this._currentLOD) {
  17833. this._currentLOD._registerInstanceForRenderId(this, renderId);
  17834. }
  17835. };
  17836. InstancedMesh.prototype.getLOD = function (camera) {
  17837. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  17838. if (this._currentLOD === this.sourceMesh) {
  17839. return this;
  17840. }
  17841. return this._currentLOD;
  17842. };
  17843. InstancedMesh.prototype._syncSubMeshes = function () {
  17844. this.releaseSubMeshes();
  17845. if (this._sourceMesh.subMeshes) {
  17846. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  17847. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  17848. }
  17849. }
  17850. };
  17851. InstancedMesh.prototype._generatePointsArray = function () {
  17852. return this._sourceMesh._generatePointsArray();
  17853. };
  17854. // Clone
  17855. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17856. var result = this._sourceMesh.createInstance(name);
  17857. // Deep copy
  17858. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  17859. // Bounding info
  17860. this.refreshBoundingInfo();
  17861. // Parent
  17862. if (newParent) {
  17863. result.parent = newParent;
  17864. }
  17865. if (!doNotCloneChildren) {
  17866. // Children
  17867. for (var index = 0; index < this.getScene().meshes.length; index++) {
  17868. var mesh = this.getScene().meshes[index];
  17869. if (mesh.parent === this) {
  17870. mesh.clone(mesh.name, result);
  17871. }
  17872. }
  17873. }
  17874. result.computeWorldMatrix(true);
  17875. return result;
  17876. };
  17877. // Dispoe
  17878. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  17879. // Remove from mesh
  17880. var index = this._sourceMesh.instances.indexOf(this);
  17881. this._sourceMesh.instances.splice(index, 1);
  17882. _super.prototype.dispose.call(this, doNotRecurse);
  17883. };
  17884. return InstancedMesh;
  17885. })(BABYLON.AbstractMesh);
  17886. BABYLON.InstancedMesh = InstancedMesh;
  17887. })(BABYLON || (BABYLON = {}));
  17888. var BABYLON;
  17889. (function (BABYLON) {
  17890. var _InstancesBatch = (function () {
  17891. function _InstancesBatch() {
  17892. this.mustReturn = false;
  17893. this.visibleInstances = new Array();
  17894. this.renderSelf = new Array();
  17895. }
  17896. return _InstancesBatch;
  17897. })();
  17898. BABYLON._InstancesBatch = _InstancesBatch;
  17899. var Mesh = (function (_super) {
  17900. __extends(Mesh, _super);
  17901. /**
  17902. * @constructor
  17903. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  17904. * @param {Scene} scene The scene to add this mesh to.
  17905. * @param {Node} parent The parent of this mesh, if it has one
  17906. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  17907. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  17908. * When false, achieved by calling a clone(), also passing False.
  17909. * This will make creation of children, recursive.
  17910. */
  17911. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  17912. if (parent === void 0) { parent = null; }
  17913. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17914. _super.call(this, name, scene);
  17915. // Events
  17916. /**
  17917. * An event triggered before rendering the mesh
  17918. * @type {BABYLON.Observable}
  17919. */
  17920. this.onBeforeRenderObservable = new BABYLON.Observable();
  17921. /**
  17922. * An event triggered after rendering the mesh
  17923. * @type {BABYLON.Observable}
  17924. */
  17925. this.onAfterRenderObservable = new BABYLON.Observable();
  17926. /**
  17927. * An event triggered before drawing the mesh
  17928. * @type {BABYLON.Observable}
  17929. */
  17930. this.onBeforeDrawObservable = new BABYLON.Observable();
  17931. // Members
  17932. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17933. this.instances = new Array();
  17934. this._LODLevels = new Array();
  17935. this._visibleInstances = {};
  17936. this._renderIdForInstances = new Array();
  17937. this._batchCache = new _InstancesBatch();
  17938. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  17939. this._sideOrientation = Mesh._DEFAULTSIDE;
  17940. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  17941. if (source) {
  17942. // Geometry
  17943. if (source._geometry) {
  17944. source._geometry.applyToMesh(this);
  17945. }
  17946. // Deep copy
  17947. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  17948. // Pivot
  17949. this.setPivotMatrix(source.getPivotMatrix());
  17950. this.id = name + "." + source.id;
  17951. // Material
  17952. this.material = source.material;
  17953. var index;
  17954. if (!doNotCloneChildren) {
  17955. // Children
  17956. for (index = 0; index < scene.meshes.length; index++) {
  17957. var mesh = scene.meshes[index];
  17958. if (mesh.parent === source) {
  17959. // doNotCloneChildren is always going to be False
  17960. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  17961. }
  17962. }
  17963. }
  17964. // Physics clone
  17965. var physicsEngine = this.getScene().getPhysicsEngine();
  17966. if (clonePhysicsImpostor && physicsEngine) {
  17967. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  17968. if (impostor) {
  17969. this.physicsImpostor = impostor.clone(this);
  17970. }
  17971. }
  17972. // Particles
  17973. for (index = 0; index < scene.particleSystems.length; index++) {
  17974. var system = scene.particleSystems[index];
  17975. if (system.emitter === source) {
  17976. system.clone(system.name, this);
  17977. }
  17978. }
  17979. this.computeWorldMatrix(true);
  17980. }
  17981. // Parent
  17982. if (parent !== null) {
  17983. this.parent = parent;
  17984. }
  17985. }
  17986. Object.defineProperty(Mesh, "FRONTSIDE", {
  17987. /**
  17988. * Mesh side orientation : usually the external or front surface
  17989. */
  17990. get: function () {
  17991. return Mesh._FRONTSIDE;
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(Mesh, "BACKSIDE", {
  17997. /**
  17998. * Mesh side orientation : usually the internal or back surface
  17999. */
  18000. get: function () {
  18001. return Mesh._BACKSIDE;
  18002. },
  18003. enumerable: true,
  18004. configurable: true
  18005. });
  18006. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18007. /**
  18008. * Mesh side orientation : both internal and external or front and back surfaces
  18009. */
  18010. get: function () {
  18011. return Mesh._DOUBLESIDE;
  18012. },
  18013. enumerable: true,
  18014. configurable: true
  18015. });
  18016. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18017. /**
  18018. * Mesh side orientation : by default, `FRONTSIDE`
  18019. */
  18020. get: function () {
  18021. return Mesh._DEFAULTSIDE;
  18022. },
  18023. enumerable: true,
  18024. configurable: true
  18025. });
  18026. Object.defineProperty(Mesh, "NO_CAP", {
  18027. /**
  18028. * Mesh cap setting : no cap
  18029. */
  18030. get: function () {
  18031. return Mesh._NO_CAP;
  18032. },
  18033. enumerable: true,
  18034. configurable: true
  18035. });
  18036. Object.defineProperty(Mesh, "CAP_START", {
  18037. /**
  18038. * Mesh cap setting : one cap at the beginning of the mesh
  18039. */
  18040. get: function () {
  18041. return Mesh._CAP_START;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. Object.defineProperty(Mesh, "CAP_END", {
  18047. /**
  18048. * Mesh cap setting : one cap at the end of the mesh
  18049. */
  18050. get: function () {
  18051. return Mesh._CAP_END;
  18052. },
  18053. enumerable: true,
  18054. configurable: true
  18055. });
  18056. Object.defineProperty(Mesh, "CAP_ALL", {
  18057. /**
  18058. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18059. */
  18060. get: function () {
  18061. return Mesh._CAP_ALL;
  18062. },
  18063. enumerable: true,
  18064. configurable: true
  18065. });
  18066. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18067. set: function (callback) {
  18068. if (this._onBeforeDrawObserver) {
  18069. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18070. }
  18071. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18072. },
  18073. enumerable: true,
  18074. configurable: true
  18075. });
  18076. // Methods
  18077. /**
  18078. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18079. */
  18080. Mesh.prototype.toString = function (fullDetails) {
  18081. var ret = _super.prototype.toString.call(this, fullDetails);
  18082. ret += ", n vertices: " + this.getTotalVertices();
  18083. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18084. if (this.animations) {
  18085. for (var i = 0; i < this.animations.length; i++) {
  18086. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18087. }
  18088. }
  18089. if (fullDetails) {
  18090. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18091. }
  18092. return ret;
  18093. };
  18094. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18095. get: function () {
  18096. return this._LODLevels.length > 0;
  18097. },
  18098. enumerable: true,
  18099. configurable: true
  18100. });
  18101. Mesh.prototype._sortLODLevels = function () {
  18102. this._LODLevels.sort(function (a, b) {
  18103. if (a.distance < b.distance) {
  18104. return 1;
  18105. }
  18106. if (a.distance > b.distance) {
  18107. return -1;
  18108. }
  18109. return 0;
  18110. });
  18111. };
  18112. /**
  18113. * Add a mesh as LOD level triggered at the given distance.
  18114. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18115. * @param {number} distance The distance from the center of the object to show this level
  18116. * @param {Mesh} mesh The mesh to be added as LOD level
  18117. * @return {Mesh} This mesh (for chaining)
  18118. */
  18119. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18120. if (mesh && mesh._masterMesh) {
  18121. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18122. return this;
  18123. }
  18124. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18125. this._LODLevels.push(level);
  18126. if (mesh) {
  18127. mesh._masterMesh = this;
  18128. }
  18129. this._sortLODLevels();
  18130. return this;
  18131. };
  18132. /**
  18133. * Returns the LOD level mesh at the passed distance or null if not found.
  18134. * It is related to the method `addLODLevel(distance, mesh)`.
  18135. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18136. */
  18137. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18138. for (var index = 0; index < this._LODLevels.length; index++) {
  18139. var level = this._LODLevels[index];
  18140. if (level.distance === distance) {
  18141. return level.mesh;
  18142. }
  18143. }
  18144. return null;
  18145. };
  18146. /**
  18147. * Remove a mesh from the LOD array
  18148. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18149. * @param {Mesh} mesh The mesh to be removed.
  18150. * @return {Mesh} This mesh (for chaining)
  18151. */
  18152. Mesh.prototype.removeLODLevel = function (mesh) {
  18153. for (var index = 0; index < this._LODLevels.length; index++) {
  18154. if (this._LODLevels[index].mesh === mesh) {
  18155. this._LODLevels.splice(index, 1);
  18156. if (mesh) {
  18157. mesh._masterMesh = null;
  18158. }
  18159. }
  18160. }
  18161. this._sortLODLevels();
  18162. return this;
  18163. };
  18164. /**
  18165. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18166. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18167. */
  18168. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18169. if (!this._LODLevels || this._LODLevels.length === 0) {
  18170. return this;
  18171. }
  18172. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18173. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18174. if (this.onLODLevelSelection) {
  18175. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18176. }
  18177. return this;
  18178. }
  18179. for (var index = 0; index < this._LODLevels.length; index++) {
  18180. var level = this._LODLevels[index];
  18181. if (level.distance < distanceToCamera) {
  18182. if (level.mesh) {
  18183. level.mesh._preActivate();
  18184. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18185. }
  18186. if (this.onLODLevelSelection) {
  18187. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18188. }
  18189. return level.mesh;
  18190. }
  18191. }
  18192. if (this.onLODLevelSelection) {
  18193. this.onLODLevelSelection(distanceToCamera, this, this);
  18194. }
  18195. return this;
  18196. };
  18197. Object.defineProperty(Mesh.prototype, "geometry", {
  18198. /**
  18199. * Returns the mesh internal Geometry object.
  18200. */
  18201. get: function () {
  18202. return this._geometry;
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. /**
  18208. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18209. */
  18210. Mesh.prototype.getTotalVertices = function () {
  18211. if (!this._geometry) {
  18212. return 0;
  18213. }
  18214. return this._geometry.getTotalVertices();
  18215. };
  18216. /**
  18217. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18218. * 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.
  18219. * Returns null if the mesh has no geometry or no vertex buffer.
  18220. * Possible `kind` values :
  18221. * - BABYLON.VertexBuffer.PositionKind
  18222. * - BABYLON.VertexBuffer.UVKind
  18223. * - BABYLON.VertexBuffer.UV2Kind
  18224. * - BABYLON.VertexBuffer.UV3Kind
  18225. * - BABYLON.VertexBuffer.UV4Kind
  18226. * - BABYLON.VertexBuffer.UV5Kind
  18227. * - BABYLON.VertexBuffer.UV6Kind
  18228. * - BABYLON.VertexBuffer.ColorKind
  18229. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18230. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18231. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18232. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18233. */
  18234. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18235. if (!this._geometry) {
  18236. return null;
  18237. }
  18238. return this._geometry.getVerticesData(kind, copyWhenShared);
  18239. };
  18240. /**
  18241. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18242. * Returns `undefined` if the mesh has no geometry.
  18243. * Possible `kind` values :
  18244. * - BABYLON.VertexBuffer.PositionKind
  18245. * - BABYLON.VertexBuffer.UVKind
  18246. * - BABYLON.VertexBuffer.UV2Kind
  18247. * - BABYLON.VertexBuffer.UV3Kind
  18248. * - BABYLON.VertexBuffer.UV4Kind
  18249. * - BABYLON.VertexBuffer.UV5Kind
  18250. * - BABYLON.VertexBuffer.UV6Kind
  18251. * - BABYLON.VertexBuffer.ColorKind
  18252. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18253. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18254. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18255. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18256. */
  18257. Mesh.prototype.getVertexBuffer = function (kind) {
  18258. if (!this._geometry) {
  18259. return undefined;
  18260. }
  18261. return this._geometry.getVertexBuffer(kind);
  18262. };
  18263. /**
  18264. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18265. * Possible `kind` values :
  18266. * - BABYLON.VertexBuffer.PositionKind
  18267. * - BABYLON.VertexBuffer.UVKind
  18268. * - BABYLON.VertexBuffer.UV2Kind
  18269. * - BABYLON.VertexBuffer.UV3Kind
  18270. * - BABYLON.VertexBuffer.UV4Kind
  18271. * - BABYLON.VertexBuffer.UV5Kind
  18272. * - BABYLON.VertexBuffer.UV6Kind
  18273. * - BABYLON.VertexBuffer.ColorKind
  18274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18278. */
  18279. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18280. if (!this._geometry) {
  18281. if (this._delayInfo) {
  18282. return this._delayInfo.indexOf(kind) !== -1;
  18283. }
  18284. return false;
  18285. }
  18286. return this._geometry.isVerticesDataPresent(kind);
  18287. };
  18288. /**
  18289. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18290. * Possible `kind` values :
  18291. * - BABYLON.VertexBuffer.PositionKind
  18292. * - BABYLON.VertexBuffer.UVKind
  18293. * - BABYLON.VertexBuffer.UV2Kind
  18294. * - BABYLON.VertexBuffer.UV3Kind
  18295. * - BABYLON.VertexBuffer.UV4Kind
  18296. * - BABYLON.VertexBuffer.UV5Kind
  18297. * - BABYLON.VertexBuffer.UV6Kind
  18298. * - BABYLON.VertexBuffer.ColorKind
  18299. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18300. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18301. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18302. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18303. */
  18304. Mesh.prototype.getVerticesDataKinds = function () {
  18305. if (!this._geometry) {
  18306. var result = [];
  18307. if (this._delayInfo) {
  18308. for (var kind in this._delayInfo) {
  18309. result.push(kind);
  18310. }
  18311. }
  18312. return result;
  18313. }
  18314. return this._geometry.getVerticesDataKinds();
  18315. };
  18316. /**
  18317. * Returns a positive integer : the total number of indices in this mesh geometry.
  18318. * Returns zero if the mesh has no geometry.
  18319. */
  18320. Mesh.prototype.getTotalIndices = function () {
  18321. if (!this._geometry) {
  18322. return 0;
  18323. }
  18324. return this._geometry.getTotalIndices();
  18325. };
  18326. /**
  18327. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18328. * 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.
  18329. * Returns an empty array if the mesh has no geometry.
  18330. */
  18331. Mesh.prototype.getIndices = function (copyWhenShared) {
  18332. if (!this._geometry) {
  18333. return [];
  18334. }
  18335. return this._geometry.getIndices(copyWhenShared);
  18336. };
  18337. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18338. get: function () {
  18339. return this._masterMesh !== null && this._masterMesh !== undefined;
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. /**
  18345. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18346. */
  18347. Mesh.prototype.isReady = function () {
  18348. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18349. return false;
  18350. }
  18351. return _super.prototype.isReady.call(this);
  18352. };
  18353. /**
  18354. * Boolean : true if the mesh has been disposed.
  18355. */
  18356. Mesh.prototype.isDisposed = function () {
  18357. return this._isDisposed;
  18358. };
  18359. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18360. get: function () {
  18361. return this._sideOrientation;
  18362. },
  18363. /**
  18364. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18365. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18366. */
  18367. set: function (sideO) {
  18368. this._sideOrientation = sideO;
  18369. },
  18370. enumerable: true,
  18371. configurable: true
  18372. });
  18373. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18374. /**
  18375. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18376. * This property is pertinent only for updatable parametric shapes.
  18377. */
  18378. get: function () {
  18379. return this._areNormalsFrozen;
  18380. },
  18381. enumerable: true,
  18382. configurable: true
  18383. });
  18384. /**
  18385. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18386. * It has no effect at all on other shapes.
  18387. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18388. */
  18389. Mesh.prototype.freezeNormals = function () {
  18390. this._areNormalsFrozen = true;
  18391. };
  18392. /**
  18393. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18394. * It has no effect at all on other shapes.
  18395. * It reactivates the mesh normals computation if it was previously frozen.
  18396. */
  18397. Mesh.prototype.unfreezeNormals = function () {
  18398. this._areNormalsFrozen = false;
  18399. };
  18400. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18401. /**
  18402. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18403. */
  18404. set: function (count) {
  18405. this._overridenInstanceCount = count;
  18406. },
  18407. enumerable: true,
  18408. configurable: true
  18409. });
  18410. // Methods
  18411. Mesh.prototype._preActivate = function () {
  18412. var sceneRenderId = this.getScene().getRenderId();
  18413. if (this._preActivateId === sceneRenderId) {
  18414. return;
  18415. }
  18416. this._preActivateId = sceneRenderId;
  18417. this._visibleInstances = null;
  18418. };
  18419. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18420. if (this._visibleInstances) {
  18421. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18422. }
  18423. };
  18424. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18425. if (!this._visibleInstances) {
  18426. this._visibleInstances = {};
  18427. this._visibleInstances.defaultRenderId = renderId;
  18428. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18429. }
  18430. if (!this._visibleInstances[renderId]) {
  18431. this._visibleInstances[renderId] = new Array();
  18432. }
  18433. this._visibleInstances[renderId].push(instance);
  18434. };
  18435. /**
  18436. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18437. * This means the mesh underlying bounding box and sphere are recomputed.
  18438. */
  18439. Mesh.prototype.refreshBoundingInfo = function () {
  18440. if (this._boundingInfo.isLocked) {
  18441. return;
  18442. }
  18443. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18444. if (data) {
  18445. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18446. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18447. }
  18448. if (this.subMeshes) {
  18449. for (var index = 0; index < this.subMeshes.length; index++) {
  18450. this.subMeshes[index].refreshBoundingInfo();
  18451. }
  18452. }
  18453. this._updateBoundingInfo();
  18454. };
  18455. Mesh.prototype._createGlobalSubMesh = function () {
  18456. var totalVertices = this.getTotalVertices();
  18457. if (!totalVertices || !this.getIndices()) {
  18458. return null;
  18459. }
  18460. this.releaseSubMeshes();
  18461. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18462. };
  18463. Mesh.prototype.subdivide = function (count) {
  18464. if (count < 1) {
  18465. return;
  18466. }
  18467. var totalIndices = this.getTotalIndices();
  18468. var subdivisionSize = (totalIndices / count) | 0;
  18469. var offset = 0;
  18470. // Ensure that subdivisionSize is a multiple of 3
  18471. while (subdivisionSize % 3 !== 0) {
  18472. subdivisionSize++;
  18473. }
  18474. this.releaseSubMeshes();
  18475. for (var index = 0; index < count; index++) {
  18476. if (offset >= totalIndices) {
  18477. break;
  18478. }
  18479. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18480. offset += subdivisionSize;
  18481. }
  18482. this.synchronizeInstances();
  18483. };
  18484. /**
  18485. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18486. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18487. * The `data` are either a numeric array either a Float32Array.
  18488. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18489. * 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).
  18490. * Note that a new underlying VertexBuffer object is created each call.
  18491. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18492. *
  18493. * Possible `kind` values :
  18494. * - BABYLON.VertexBuffer.PositionKind
  18495. * - BABYLON.VertexBuffer.UVKind
  18496. * - BABYLON.VertexBuffer.UV2Kind
  18497. * - BABYLON.VertexBuffer.UV3Kind
  18498. * - BABYLON.VertexBuffer.UV4Kind
  18499. * - BABYLON.VertexBuffer.UV5Kind
  18500. * - BABYLON.VertexBuffer.UV6Kind
  18501. * - BABYLON.VertexBuffer.ColorKind
  18502. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18503. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18504. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18505. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18506. */
  18507. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18508. if (!this._geometry) {
  18509. var vertexData = new BABYLON.VertexData();
  18510. vertexData.set(data, kind);
  18511. var scene = this.getScene();
  18512. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  18513. }
  18514. else {
  18515. this._geometry.setVerticesData(kind, data, updatable, stride);
  18516. }
  18517. };
  18518. Mesh.prototype.setVerticesBuffer = function (buffer) {
  18519. if (!this._geometry) {
  18520. var scene = this.getScene();
  18521. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  18522. }
  18523. this._geometry.setVerticesBuffer(buffer);
  18524. };
  18525. /**
  18526. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18527. * If the mesh has no geometry, it is simply returned as it is.
  18528. * The `data` are either a numeric array either a Float32Array.
  18529. * No new underlying VertexBuffer object is created.
  18530. * 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.
  18531. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18532. *
  18533. * Possible `kind` values :
  18534. * - BABYLON.VertexBuffer.PositionKind
  18535. * - BABYLON.VertexBuffer.UVKind
  18536. * - BABYLON.VertexBuffer.UV2Kind
  18537. * - BABYLON.VertexBuffer.UV3Kind
  18538. * - BABYLON.VertexBuffer.UV4Kind
  18539. * - BABYLON.VertexBuffer.UV5Kind
  18540. * - BABYLON.VertexBuffer.UV6Kind
  18541. * - BABYLON.VertexBuffer.ColorKind
  18542. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18543. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18544. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18545. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18546. */
  18547. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18548. if (!this._geometry) {
  18549. return;
  18550. }
  18551. if (!makeItUnique) {
  18552. this._geometry.updateVerticesData(kind, data, updateExtends);
  18553. }
  18554. else {
  18555. this.makeGeometryUnique();
  18556. this.updateVerticesData(kind, data, updateExtends, false);
  18557. }
  18558. };
  18559. /**
  18560. * Deprecated since BabylonJS v2.3
  18561. */
  18562. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  18563. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  18564. if (!this._geometry) {
  18565. return;
  18566. }
  18567. if (!makeItUnique) {
  18568. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  18569. }
  18570. else {
  18571. this.makeGeometryUnique();
  18572. this.updateVerticesDataDirectly(kind, data, offset, false);
  18573. }
  18574. };
  18575. /**
  18576. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  18577. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  18578. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  18579. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  18580. */
  18581. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  18582. if (computeNormals === void 0) { computeNormals = true; }
  18583. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18584. positionFunction(positions);
  18585. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  18586. if (computeNormals) {
  18587. var indices = this.getIndices();
  18588. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18589. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  18590. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  18591. }
  18592. };
  18593. Mesh.prototype.makeGeometryUnique = function () {
  18594. if (!this._geometry) {
  18595. return;
  18596. }
  18597. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  18598. geometry.applyToMesh(this);
  18599. };
  18600. /**
  18601. * Sets the mesh indices.
  18602. * Expects an array populated with integers or a Int32Array.
  18603. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18604. * This method creates a new index buffer each call.
  18605. */
  18606. Mesh.prototype.setIndices = function (indices, totalVertices) {
  18607. if (!this._geometry) {
  18608. var vertexData = new BABYLON.VertexData();
  18609. vertexData.indices = indices;
  18610. var scene = this.getScene();
  18611. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  18612. }
  18613. else {
  18614. this._geometry.setIndices(indices, totalVertices);
  18615. }
  18616. };
  18617. /**
  18618. * Invert the geometry to move from a right handed system to a left handed one.
  18619. */
  18620. Mesh.prototype.toLeftHanded = function () {
  18621. if (!this._geometry) {
  18622. return;
  18623. }
  18624. this._geometry.toLeftHanded();
  18625. };
  18626. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  18627. var engine = this.getScene().getEngine();
  18628. // Wireframe
  18629. var indexToBind;
  18630. if (this._unIndexed) {
  18631. indexToBind = null;
  18632. }
  18633. else {
  18634. switch (fillMode) {
  18635. case BABYLON.Material.PointFillMode:
  18636. indexToBind = null;
  18637. break;
  18638. case BABYLON.Material.WireFrameFillMode:
  18639. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  18640. break;
  18641. default:
  18642. case BABYLON.Material.TriangleFillMode:
  18643. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  18644. break;
  18645. }
  18646. }
  18647. // VBOs
  18648. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  18649. };
  18650. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  18651. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18652. return;
  18653. }
  18654. this.onBeforeDrawObservable.notifyObservers(this);
  18655. var engine = this.getScene().getEngine();
  18656. // Draw order
  18657. switch (fillMode) {
  18658. case BABYLON.Material.PointFillMode:
  18659. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18660. break;
  18661. case BABYLON.Material.WireFrameFillMode:
  18662. if (this._unIndexed) {
  18663. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18664. }
  18665. else {
  18666. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  18667. }
  18668. break;
  18669. default:
  18670. if (this._unIndexed) {
  18671. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  18672. }
  18673. else {
  18674. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  18675. }
  18676. }
  18677. };
  18678. /**
  18679. * Registers for this mesh a javascript function called just before the rendering process.
  18680. * This function is passed the current mesh and doesn't return anything.
  18681. */
  18682. Mesh.prototype.registerBeforeRender = function (func) {
  18683. this.onBeforeRenderObservable.add(func);
  18684. };
  18685. /**
  18686. * Disposes a previously registered javascript function called before the rendering.
  18687. * This function is passed the current mesh and doesn't return anything.
  18688. */
  18689. Mesh.prototype.unregisterBeforeRender = function (func) {
  18690. this.onBeforeRenderObservable.removeCallback(func);
  18691. };
  18692. /**
  18693. * Registers for this mesh a javascript function called just after the rendering is complete.
  18694. * This function is passed the current mesh and doesn't return anything.
  18695. */
  18696. Mesh.prototype.registerAfterRender = function (func) {
  18697. this.onAfterRenderObservable.add(func);
  18698. };
  18699. /**
  18700. * Disposes a previously registered javascript function called after the rendering.
  18701. * This function is passed the current mesh and doesn't return anything.
  18702. */
  18703. Mesh.prototype.unregisterAfterRender = function (func) {
  18704. this.onAfterRenderObservable.removeCallback(func);
  18705. };
  18706. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  18707. var scene = this.getScene();
  18708. this._batchCache.mustReturn = false;
  18709. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  18710. this._batchCache.visibleInstances[subMeshId] = null;
  18711. if (this._visibleInstances) {
  18712. var currentRenderId = scene.getRenderId();
  18713. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  18714. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  18715. var selfRenderId = this._renderId;
  18716. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  18717. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  18718. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  18719. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  18720. }
  18721. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  18722. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  18723. this._batchCache.mustReturn = true;
  18724. return this._batchCache;
  18725. }
  18726. if (currentRenderId !== selfRenderId) {
  18727. this._batchCache.renderSelf[subMeshId] = false;
  18728. }
  18729. }
  18730. this._renderIdForInstances[subMeshId] = currentRenderId;
  18731. }
  18732. return this._batchCache;
  18733. };
  18734. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  18735. var visibleInstances = batch.visibleInstances[subMesh._id];
  18736. var matricesCount = visibleInstances.length + 1;
  18737. var bufferSize = matricesCount * 16 * 4;
  18738. var currentInstancesBufferSize = this._instancesBufferSize;
  18739. var instancesBuffer = this._instancesBuffer;
  18740. while (this._instancesBufferSize < bufferSize) {
  18741. this._instancesBufferSize *= 2;
  18742. }
  18743. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  18744. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  18745. }
  18746. var offset = 0;
  18747. var instancesCount = 0;
  18748. var world = this.getWorldMatrix();
  18749. if (batch.renderSelf[subMesh._id]) {
  18750. world.copyToArray(this._instancesData, offset);
  18751. offset += 16;
  18752. instancesCount++;
  18753. }
  18754. if (visibleInstances) {
  18755. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  18756. var instance = visibleInstances[instanceIndex];
  18757. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  18758. offset += 16;
  18759. instancesCount++;
  18760. }
  18761. }
  18762. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  18763. if (instancesBuffer) {
  18764. instancesBuffer.dispose();
  18765. }
  18766. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  18767. this._instancesBuffer = instancesBuffer;
  18768. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  18769. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  18770. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  18771. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  18772. }
  18773. else {
  18774. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  18775. }
  18776. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  18777. this._draw(subMesh, fillMode, instancesCount);
  18778. engine.unbindInstanceAttributes();
  18779. };
  18780. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  18781. var scene = this.getScene();
  18782. var engine = scene.getEngine();
  18783. if (hardwareInstancedRendering) {
  18784. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  18785. }
  18786. else {
  18787. if (batch.renderSelf[subMesh._id]) {
  18788. // Draw
  18789. if (onBeforeDraw) {
  18790. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  18791. }
  18792. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  18793. }
  18794. if (batch.visibleInstances[subMesh._id]) {
  18795. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  18796. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  18797. // World
  18798. var world = instance.getWorldMatrix();
  18799. if (onBeforeDraw) {
  18800. onBeforeDraw(true, world, effectiveMaterial);
  18801. }
  18802. // Draw
  18803. this._draw(subMesh, fillMode);
  18804. }
  18805. }
  18806. }
  18807. };
  18808. /**
  18809. * Triggers the draw call for the mesh.
  18810. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  18811. */
  18812. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  18813. var scene = this.getScene();
  18814. // Managing instances
  18815. var batch = this._getInstancesRenderList(subMesh._id);
  18816. if (batch.mustReturn) {
  18817. return;
  18818. }
  18819. // Checking geometry state
  18820. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  18821. return;
  18822. }
  18823. var callbackIndex;
  18824. this.onBeforeRenderObservable.notifyObservers(this);
  18825. var engine = scene.getEngine();
  18826. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  18827. // Material
  18828. var effectiveMaterial = subMesh.getMaterial();
  18829. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  18830. return;
  18831. }
  18832. // Outline - step 1
  18833. var savedDepthWrite = engine.getDepthWrite();
  18834. if (this.renderOutline) {
  18835. engine.setDepthWrite(false);
  18836. scene.getOutlineRenderer().render(subMesh, batch);
  18837. engine.setDepthWrite(savedDepthWrite);
  18838. }
  18839. effectiveMaterial._preBind();
  18840. var effect = effectiveMaterial.getEffect();
  18841. // Bind
  18842. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  18843. this._bind(subMesh, effect, fillMode);
  18844. var world = this.getWorldMatrix();
  18845. effectiveMaterial.bind(world, this);
  18846. // Alpha mode
  18847. if (enableAlphaMode) {
  18848. engine.setAlphaMode(effectiveMaterial.alphaMode);
  18849. }
  18850. // Draw
  18851. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  18852. // Unbind
  18853. effectiveMaterial.unbind();
  18854. // Outline - step 2
  18855. if (this.renderOutline && savedDepthWrite) {
  18856. engine.setDepthWrite(true);
  18857. engine.setColorWrite(false);
  18858. scene.getOutlineRenderer().render(subMesh, batch);
  18859. engine.setColorWrite(true);
  18860. }
  18861. // Overlay
  18862. if (this.renderOverlay) {
  18863. var currentMode = engine.getAlphaMode();
  18864. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  18865. scene.getOutlineRenderer().render(subMesh, batch, true);
  18866. engine.setAlphaMode(currentMode);
  18867. }
  18868. this.onAfterRenderObservable.notifyObservers(this);
  18869. };
  18870. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  18871. if (isInstance) {
  18872. effectiveMaterial.bindOnlyWorldMatrix(world);
  18873. }
  18874. };
  18875. /**
  18876. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  18877. */
  18878. Mesh.prototype.getEmittedParticleSystems = function () {
  18879. var results = new Array();
  18880. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18881. var particleSystem = this.getScene().particleSystems[index];
  18882. if (particleSystem.emitter === this) {
  18883. results.push(particleSystem);
  18884. }
  18885. }
  18886. return results;
  18887. };
  18888. /**
  18889. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  18890. */
  18891. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  18892. var results = new Array();
  18893. var descendants = this.getDescendants();
  18894. descendants.push(this);
  18895. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  18896. var particleSystem = this.getScene().particleSystems[index];
  18897. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  18898. results.push(particleSystem);
  18899. }
  18900. }
  18901. return results;
  18902. };
  18903. Mesh.prototype._checkDelayState = function () {
  18904. var scene = this.getScene();
  18905. if (this._geometry) {
  18906. this._geometry.load(scene);
  18907. }
  18908. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  18910. this._queueLoad(this, scene);
  18911. }
  18912. };
  18913. Mesh.prototype._queueLoad = function (mesh, scene) {
  18914. var _this = this;
  18915. scene._addPendingData(mesh);
  18916. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  18917. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  18918. if (data instanceof ArrayBuffer) {
  18919. _this._delayLoadingFunction(data, _this);
  18920. }
  18921. else {
  18922. _this._delayLoadingFunction(JSON.parse(data), _this);
  18923. }
  18924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18925. scene._removePendingData(_this);
  18926. }, function () { }, scene.database, getBinaryData);
  18927. };
  18928. /**
  18929. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  18930. */
  18931. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  18932. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18933. return false;
  18934. }
  18935. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  18936. return false;
  18937. }
  18938. this._checkDelayState();
  18939. return true;
  18940. };
  18941. /**
  18942. * Sets the mesh material by the material or multiMaterial `id` property.
  18943. * The material `id` is a string identifying the material or the multiMaterial.
  18944. * This method returns nothing.
  18945. */
  18946. Mesh.prototype.setMaterialByID = function (id) {
  18947. var materials = this.getScene().materials;
  18948. var index;
  18949. for (index = 0; index < materials.length; index++) {
  18950. if (materials[index].id === id) {
  18951. this.material = materials[index];
  18952. return;
  18953. }
  18954. }
  18955. // Multi
  18956. var multiMaterials = this.getScene().multiMaterials;
  18957. for (index = 0; index < multiMaterials.length; index++) {
  18958. if (multiMaterials[index].id === id) {
  18959. this.material = multiMaterials[index];
  18960. return;
  18961. }
  18962. }
  18963. };
  18964. /**
  18965. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  18966. */
  18967. Mesh.prototype.getAnimatables = function () {
  18968. var results = [];
  18969. if (this.material) {
  18970. results.push(this.material);
  18971. }
  18972. if (this.skeleton) {
  18973. results.push(this.skeleton);
  18974. }
  18975. return results;
  18976. };
  18977. /**
  18978. * Modifies the mesh geometry according to the passed transformation matrix.
  18979. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  18980. * The mesh normals are modified accordingly the same transformation.
  18981. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  18982. * Note that, under the hood, this method sets a new VertexBuffer each call.
  18983. */
  18984. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  18985. // Position
  18986. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18987. return;
  18988. }
  18989. var submeshes = this.subMeshes.splice(0);
  18990. this._resetPointsArrayCache();
  18991. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18992. var temp = [];
  18993. var index;
  18994. for (index = 0; index < data.length; index += 3) {
  18995. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  18996. }
  18997. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  18998. // Normals
  18999. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19000. return;
  19001. }
  19002. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19003. temp = [];
  19004. for (index = 0; index < data.length; index += 3) {
  19005. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19006. }
  19007. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19008. // flip faces?
  19009. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19010. this.flipFaces();
  19011. }
  19012. // Restore submeshes
  19013. this.releaseSubMeshes();
  19014. this.subMeshes = submeshes;
  19015. };
  19016. /**
  19017. * Modifies the mesh geometry according to its own current World Matrix.
  19018. * The mesh World Matrix is then reset.
  19019. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19020. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19021. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19022. */
  19023. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19024. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19025. this.scaling.copyFromFloats(1, 1, 1);
  19026. this.position.copyFromFloats(0, 0, 0);
  19027. this.rotation.copyFromFloats(0, 0, 0);
  19028. //only if quaternion is already set
  19029. if (this.rotationQuaternion) {
  19030. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19031. }
  19032. this._worldMatrix = BABYLON.Matrix.Identity();
  19033. };
  19034. // Cache
  19035. Mesh.prototype._resetPointsArrayCache = function () {
  19036. this._positions = null;
  19037. };
  19038. Mesh.prototype._generatePointsArray = function () {
  19039. if (this._positions)
  19040. return true;
  19041. this._positions = [];
  19042. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19043. if (!data) {
  19044. return false;
  19045. }
  19046. for (var index = 0; index < data.length; index += 3) {
  19047. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19048. }
  19049. return true;
  19050. };
  19051. /**
  19052. * Returns a new Mesh object generated from the current mesh properties.
  19053. * This method must not get confused with createInstance().
  19054. * The parameter `name` is a string, the name given to the new mesh.
  19055. * The optional parameter `newParent` can be any Node object (default `null`).
  19056. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19057. * 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.
  19058. */
  19059. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19060. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19061. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19062. };
  19063. /**
  19064. * Disposes the mesh.
  19065. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19066. */
  19067. Mesh.prototype.dispose = function (doNotRecurse) {
  19068. if (this._geometry) {
  19069. this._geometry.releaseForMesh(this, true);
  19070. }
  19071. // Instances
  19072. if (this._instancesBuffer) {
  19073. this._instancesBuffer.dispose();
  19074. this._instancesBuffer = null;
  19075. }
  19076. while (this.instances.length) {
  19077. this.instances[0].dispose();
  19078. }
  19079. _super.prototype.dispose.call(this, doNotRecurse);
  19080. };
  19081. /**
  19082. * Modifies the mesh geometry according to a displacement map.
  19083. * 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.
  19084. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19085. * This method returns nothing.
  19086. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19087. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19088. * 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.
  19089. */
  19090. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19091. var _this = this;
  19092. var scene = this.getScene();
  19093. var onload = function (img) {
  19094. // Getting height map data
  19095. var canvas = document.createElement("canvas");
  19096. var context = canvas.getContext("2d");
  19097. var heightMapWidth = img.width;
  19098. var heightMapHeight = img.height;
  19099. canvas.width = heightMapWidth;
  19100. canvas.height = heightMapHeight;
  19101. context.drawImage(img, 0, 0);
  19102. // Create VertexData from map data
  19103. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19104. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19105. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19106. //execute success callback, if set
  19107. if (onSuccess) {
  19108. onSuccess(_this);
  19109. }
  19110. };
  19111. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19112. };
  19113. /**
  19114. * Modifies the mesh geometry according to a displacementMap buffer.
  19115. * 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.
  19116. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19117. * This method returns nothing.
  19118. * 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.
  19119. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19120. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19121. */
  19122. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19123. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19124. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19125. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19126. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19127. return;
  19128. }
  19129. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19130. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19131. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19132. var position = BABYLON.Vector3.Zero();
  19133. var normal = BABYLON.Vector3.Zero();
  19134. var uv = BABYLON.Vector2.Zero();
  19135. for (var index = 0; index < positions.length; index += 3) {
  19136. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19137. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19138. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19139. // Compute height
  19140. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19141. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19142. var pos = (u + v * heightMapWidth) * 4;
  19143. var r = buffer[pos] / 255.0;
  19144. var g = buffer[pos + 1] / 255.0;
  19145. var b = buffer[pos + 2] / 255.0;
  19146. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19147. normal.normalize();
  19148. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19149. position = position.add(normal);
  19150. position.toArray(positions, index);
  19151. }
  19152. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19153. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19154. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19155. };
  19156. /**
  19157. * Modify the mesh to get a flat shading rendering.
  19158. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19159. * This method returns nothing.
  19160. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19161. */
  19162. Mesh.prototype.convertToFlatShadedMesh = function () {
  19163. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19164. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19165. var kinds = this.getVerticesDataKinds();
  19166. var vbs = [];
  19167. var data = [];
  19168. var newdata = [];
  19169. var updatableNormals = false;
  19170. var kindIndex;
  19171. var kind;
  19172. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19173. kind = kinds[kindIndex];
  19174. var vertexBuffer = this.getVertexBuffer(kind);
  19175. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19176. updatableNormals = vertexBuffer.isUpdatable();
  19177. kinds.splice(kindIndex, 1);
  19178. kindIndex--;
  19179. continue;
  19180. }
  19181. vbs[kind] = vertexBuffer;
  19182. data[kind] = vbs[kind].getData();
  19183. newdata[kind] = [];
  19184. }
  19185. // Save previous submeshes
  19186. var previousSubmeshes = this.subMeshes.slice(0);
  19187. var indices = this.getIndices();
  19188. var totalIndices = this.getTotalIndices();
  19189. // Generating unique vertices per face
  19190. var index;
  19191. for (index = 0; index < totalIndices; index++) {
  19192. var vertexIndex = indices[index];
  19193. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19194. kind = kinds[kindIndex];
  19195. var stride = vbs[kind].getStrideSize();
  19196. for (var offset = 0; offset < stride; offset++) {
  19197. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19198. }
  19199. }
  19200. }
  19201. // Updating faces & normal
  19202. var normals = [];
  19203. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19204. for (index = 0; index < totalIndices; index += 3) {
  19205. indices[index] = index;
  19206. indices[index + 1] = index + 1;
  19207. indices[index + 2] = index + 2;
  19208. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19209. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19210. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19211. var p1p2 = p1.subtract(p2);
  19212. var p3p2 = p3.subtract(p2);
  19213. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19214. // Store same normals for every vertex
  19215. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19216. normals.push(normal.x);
  19217. normals.push(normal.y);
  19218. normals.push(normal.z);
  19219. }
  19220. }
  19221. this.setIndices(indices);
  19222. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19223. // Updating vertex buffers
  19224. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19225. kind = kinds[kindIndex];
  19226. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19227. }
  19228. // Updating submeshes
  19229. this.releaseSubMeshes();
  19230. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19231. var previousOne = previousSubmeshes[submeshIndex];
  19232. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19233. }
  19234. this.synchronizeInstances();
  19235. };
  19236. /**
  19237. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19238. * In other words, more vertices, no more indices and a single bigger VBO.
  19239. * This method returns nothing.
  19240. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19241. *
  19242. */
  19243. Mesh.prototype.convertToUnIndexedMesh = function () {
  19244. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19245. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19246. var kinds = this.getVerticesDataKinds();
  19247. var vbs = [];
  19248. var data = [];
  19249. var newdata = [];
  19250. var updatableNormals = false;
  19251. var kindIndex;
  19252. var kind;
  19253. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19254. kind = kinds[kindIndex];
  19255. var vertexBuffer = this.getVertexBuffer(kind);
  19256. vbs[kind] = vertexBuffer;
  19257. data[kind] = vbs[kind].getData();
  19258. newdata[kind] = [];
  19259. }
  19260. // Save previous submeshes
  19261. var previousSubmeshes = this.subMeshes.slice(0);
  19262. var indices = this.getIndices();
  19263. var totalIndices = this.getTotalIndices();
  19264. // Generating unique vertices per face
  19265. var index;
  19266. for (index = 0; index < totalIndices; index++) {
  19267. var vertexIndex = indices[index];
  19268. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19269. kind = kinds[kindIndex];
  19270. var stride = vbs[kind].getStrideSize();
  19271. for (var offset = 0; offset < stride; offset++) {
  19272. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19273. }
  19274. }
  19275. }
  19276. // Updating indices
  19277. for (index = 0; index < totalIndices; index += 3) {
  19278. indices[index] = index;
  19279. indices[index + 1] = index + 1;
  19280. indices[index + 2] = index + 2;
  19281. }
  19282. this.setIndices(indices);
  19283. // Updating vertex buffers
  19284. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19285. kind = kinds[kindIndex];
  19286. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19287. }
  19288. // Updating submeshes
  19289. this.releaseSubMeshes();
  19290. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19291. var previousOne = previousSubmeshes[submeshIndex];
  19292. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19293. }
  19294. this._unIndexed = true;
  19295. this.synchronizeInstances();
  19296. };
  19297. /**
  19298. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19299. * This method returns nothing.
  19300. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19301. */
  19302. Mesh.prototype.flipFaces = function (flipNormals) {
  19303. if (flipNormals === void 0) { flipNormals = false; }
  19304. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19305. var i;
  19306. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19307. for (i = 0; i < vertex_data.normals.length; i++) {
  19308. vertex_data.normals[i] *= -1;
  19309. }
  19310. }
  19311. var temp;
  19312. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19313. // reassign indices
  19314. temp = vertex_data.indices[i + 1];
  19315. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19316. vertex_data.indices[i + 2] = temp;
  19317. }
  19318. vertex_data.applyToMesh(this);
  19319. };
  19320. // Instances
  19321. /**
  19322. * Creates a new InstancedMesh object from the mesh model.
  19323. * An instance shares the same properties and the same material than its model.
  19324. * Only these properties of each instance can then be set individually :
  19325. * - position
  19326. * - rotation
  19327. * - rotationQuaternion
  19328. * - setPivotMatrix
  19329. * - scaling
  19330. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19331. * Warning : this method is not supported for Line mesh and LineSystem
  19332. */
  19333. Mesh.prototype.createInstance = function (name) {
  19334. return new BABYLON.InstancedMesh(name, this);
  19335. };
  19336. /**
  19337. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19338. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19339. * This method returns nothing.
  19340. */
  19341. Mesh.prototype.synchronizeInstances = function () {
  19342. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19343. var instance = this.instances[instanceIndex];
  19344. instance._syncSubMeshes();
  19345. }
  19346. };
  19347. /**
  19348. * Simplify the mesh according to the given array of settings.
  19349. * Function will return immediately and will simplify async. It returns nothing.
  19350. * @param settings a collection of simplification settings.
  19351. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19352. * @param type the type of simplification to run.
  19353. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19354. */
  19355. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19356. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19357. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19358. this.getScene().simplificationQueue.addTask({
  19359. settings: settings,
  19360. parallelProcessing: parallelProcessing,
  19361. mesh: this,
  19362. simplificationType: simplificationType,
  19363. successCallback: successCallback
  19364. });
  19365. };
  19366. /**
  19367. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19368. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19369. * This should be used together with the simplification to avoid disappearing triangles.
  19370. * @param successCallback an optional success callback to be called after the optimization finished.
  19371. */
  19372. Mesh.prototype.optimizeIndices = function (successCallback) {
  19373. var _this = this;
  19374. var indices = this.getIndices();
  19375. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19376. var vectorPositions = [];
  19377. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19378. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19379. }
  19380. var dupes = [];
  19381. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19382. var realPos = vectorPositions.length - 1 - iteration;
  19383. var testedPosition = vectorPositions[realPos];
  19384. for (var j = 0; j < realPos; ++j) {
  19385. var againstPosition = vectorPositions[j];
  19386. if (testedPosition.equals(againstPosition)) {
  19387. dupes[realPos] = j;
  19388. break;
  19389. }
  19390. }
  19391. }, function () {
  19392. for (var i = 0; i < indices.length; ++i) {
  19393. indices[i] = dupes[indices[i]] || indices[i];
  19394. }
  19395. //indices are now reordered
  19396. var originalSubMeshes = _this.subMeshes.slice(0);
  19397. _this.setIndices(indices);
  19398. _this.subMeshes = originalSubMeshes;
  19399. if (successCallback) {
  19400. successCallback(_this);
  19401. }
  19402. });
  19403. };
  19404. // Statics
  19405. /**
  19406. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19407. * The parameter `parsedMesh` is the mesh to be copied.
  19408. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19409. */
  19410. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19411. var mesh = new Mesh(parsedMesh.name, scene);
  19412. mesh.id = parsedMesh.id;
  19413. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19414. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19415. if (parsedMesh.rotationQuaternion) {
  19416. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19417. }
  19418. else if (parsedMesh.rotation) {
  19419. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19420. }
  19421. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19422. if (parsedMesh.localMatrix) {
  19423. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19424. }
  19425. else if (parsedMesh.pivotMatrix) {
  19426. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19427. }
  19428. mesh.setEnabled(parsedMesh.isEnabled);
  19429. mesh.isVisible = parsedMesh.isVisible;
  19430. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19431. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19432. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19433. if (parsedMesh.applyFog !== undefined) {
  19434. mesh.applyFog = parsedMesh.applyFog;
  19435. }
  19436. if (parsedMesh.pickable !== undefined) {
  19437. mesh.isPickable = parsedMesh.pickable;
  19438. }
  19439. if (parsedMesh.alphaIndex !== undefined) {
  19440. mesh.alphaIndex = parsedMesh.alphaIndex;
  19441. }
  19442. mesh.receiveShadows = parsedMesh.receiveShadows;
  19443. mesh.billboardMode = parsedMesh.billboardMode;
  19444. if (parsedMesh.visibility !== undefined) {
  19445. mesh.visibility = parsedMesh.visibility;
  19446. }
  19447. mesh.checkCollisions = parsedMesh.checkCollisions;
  19448. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19449. // freezeWorldMatrix
  19450. if (parsedMesh.freezeWorldMatrix) {
  19451. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19452. }
  19453. // Parent
  19454. if (parsedMesh.parentId) {
  19455. mesh._waitingParentId = parsedMesh.parentId;
  19456. }
  19457. // Actions
  19458. if (parsedMesh.actions !== undefined) {
  19459. mesh._waitingActions = parsedMesh.actions;
  19460. }
  19461. // Geometry
  19462. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19463. if (parsedMesh.delayLoadingFile) {
  19464. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19465. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19466. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19467. if (parsedMesh._binaryInfo) {
  19468. mesh._binaryInfo = parsedMesh._binaryInfo;
  19469. }
  19470. mesh._delayInfo = [];
  19471. if (parsedMesh.hasUVs) {
  19472. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19473. }
  19474. if (parsedMesh.hasUVs2) {
  19475. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19476. }
  19477. if (parsedMesh.hasUVs3) {
  19478. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19479. }
  19480. if (parsedMesh.hasUVs4) {
  19481. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19482. }
  19483. if (parsedMesh.hasUVs5) {
  19484. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19485. }
  19486. if (parsedMesh.hasUVs6) {
  19487. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19488. }
  19489. if (parsedMesh.hasColors) {
  19490. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19491. }
  19492. if (parsedMesh.hasMatricesIndices) {
  19493. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19494. }
  19495. if (parsedMesh.hasMatricesWeights) {
  19496. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19497. }
  19498. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  19499. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19500. mesh._checkDelayState();
  19501. }
  19502. }
  19503. else {
  19504. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  19505. }
  19506. // Material
  19507. if (parsedMesh.materialId) {
  19508. mesh.setMaterialByID(parsedMesh.materialId);
  19509. }
  19510. else {
  19511. mesh.material = null;
  19512. }
  19513. // Skeleton
  19514. if (parsedMesh.skeletonId > -1) {
  19515. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19516. if (parsedMesh.numBoneInfluencers) {
  19517. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  19518. }
  19519. }
  19520. // Animations
  19521. if (parsedMesh.animations) {
  19522. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19523. var parsedAnimation = parsedMesh.animations[animationIndex];
  19524. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19525. }
  19526. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  19527. }
  19528. if (parsedMesh.autoAnimate) {
  19529. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  19530. }
  19531. // Layer Mask
  19532. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19533. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19534. }
  19535. else {
  19536. mesh.layerMask = 0x0FFFFFFF;
  19537. }
  19538. //(Deprecated) physics
  19539. if (parsedMesh.physicsImpostor) {
  19540. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  19541. mass: parsedMesh.physicsMass,
  19542. friction: parsedMesh.physicsFriction,
  19543. restitution: parsedMesh.physicsRestitution
  19544. }, scene);
  19545. }
  19546. // Instances
  19547. if (parsedMesh.instances) {
  19548. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19549. var parsedInstance = parsedMesh.instances[index];
  19550. var instance = mesh.createInstance(parsedInstance.name);
  19551. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19552. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19553. if (parsedInstance.rotationQuaternion) {
  19554. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19555. }
  19556. else if (parsedInstance.rotation) {
  19557. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19558. }
  19559. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19560. instance.checkCollisions = mesh.checkCollisions;
  19561. if (parsedMesh.animations) {
  19562. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19563. parsedAnimation = parsedMesh.animations[animationIndex];
  19564. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19565. }
  19566. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  19567. }
  19568. }
  19569. }
  19570. return mesh;
  19571. };
  19572. /**
  19573. * Creates a ribbon mesh.
  19574. * Please consider using the same method from the MeshBuilder class instead.
  19575. * 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.
  19576. *
  19577. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19578. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19579. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19580. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19581. * 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.
  19582. * 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.
  19583. * 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
  19584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19585. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19587. */
  19588. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  19589. return BABYLON.MeshBuilder.CreateRibbon(name, {
  19590. pathArray: pathArray,
  19591. closeArray: closeArray,
  19592. closePath: closePath,
  19593. offset: offset,
  19594. updatable: updatable,
  19595. sideOrientation: sideOrientation,
  19596. instance: instance
  19597. }, scene);
  19598. };
  19599. /**
  19600. * Creates a plane polygonal mesh. By default, this is a disc.
  19601. * Please consider using the same method from the MeshBuilder class instead.
  19602. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19603. * 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.
  19604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19605. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19607. */
  19608. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  19609. var options = {
  19610. radius: radius,
  19611. tessellation: tessellation,
  19612. sideOrientation: sideOrientation,
  19613. updatable: updatable
  19614. };
  19615. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  19616. };
  19617. /**
  19618. * Creates a box mesh.
  19619. * Please consider using the same method from the MeshBuilder class instead.
  19620. * The parameter `size` sets the size (float) of each box side (default 1).
  19621. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19624. */
  19625. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  19626. var options = {
  19627. size: size,
  19628. sideOrientation: sideOrientation,
  19629. updatable: updatable
  19630. };
  19631. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  19632. };
  19633. /**
  19634. * Creates a sphere mesh.
  19635. * Please consider using the same method from the MeshBuilder class instead.
  19636. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19637. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19641. */
  19642. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  19643. var options = {
  19644. segments: segments,
  19645. diameterX: diameter,
  19646. diameterY: diameter,
  19647. diameterZ: diameter,
  19648. sideOrientation: sideOrientation,
  19649. updatable: updatable
  19650. };
  19651. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  19652. };
  19653. /**
  19654. * Creates a cylinder or a cone mesh.
  19655. * Please consider using the same method from the MeshBuilder class instead.
  19656. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19657. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19658. * 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.
  19659. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19660. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  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.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  19666. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  19667. if (scene !== undefined) {
  19668. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  19669. updatable = scene;
  19670. }
  19671. scene = subdivisions;
  19672. subdivisions = 1;
  19673. }
  19674. var options = {
  19675. height: height,
  19676. diameterTop: diameterTop,
  19677. diameterBottom: diameterBottom,
  19678. tessellation: tessellation,
  19679. subdivisions: subdivisions,
  19680. sideOrientation: sideOrientation,
  19681. updatable: updatable
  19682. };
  19683. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  19684. };
  19685. // Torus (Code from SharpDX.org)
  19686. /**
  19687. * Creates a torus mesh.
  19688. * Please consider using the same method from the MeshBuilder class instead.
  19689. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19690. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19691. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19695. */
  19696. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  19697. var options = {
  19698. diameter: diameter,
  19699. thickness: thickness,
  19700. tessellation: tessellation,
  19701. sideOrientation: sideOrientation,
  19702. updatable: updatable
  19703. };
  19704. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  19705. };
  19706. /**
  19707. * Creates a torus knot mesh.
  19708. * Please consider using the same method from the MeshBuilder class instead.
  19709. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19710. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19711. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19712. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19713. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19714. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19716. */
  19717. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  19718. var options = {
  19719. radius: radius,
  19720. tube: tube,
  19721. radialSegments: radialSegments,
  19722. tubularSegments: tubularSegments,
  19723. p: p,
  19724. q: q,
  19725. sideOrientation: sideOrientation,
  19726. updatable: updatable
  19727. };
  19728. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  19729. };
  19730. /**
  19731. * Creates a line mesh.
  19732. * Please consider using the same method from the MeshBuilder class instead.
  19733. * 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.
  19734. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19735. * The parameter `points` is an array successive Vector3.
  19736. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19737. * When updating an instance, remember that only point positions can change, not the number of points.
  19738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19739. */
  19740. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  19741. var options = {
  19742. points: points,
  19743. updatable: updatable,
  19744. instance: instance
  19745. };
  19746. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  19747. };
  19748. /**
  19749. * Creates a dashed line mesh.
  19750. * Please consider using the same method from the MeshBuilder class instead.
  19751. * 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.
  19752. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19753. * The parameter `points` is an array successive Vector3.
  19754. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19755. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19756. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19757. * 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
  19758. * When updating an instance, remember that only point positions can change, not the number of points.
  19759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19760. */
  19761. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  19762. var options = {
  19763. points: points,
  19764. dashSize: dashSize,
  19765. gapSize: gapSize,
  19766. dashNb: dashNb,
  19767. updatable: updatable,
  19768. instance: instance
  19769. };
  19770. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  19771. };
  19772. /**
  19773. * Creates an extruded shape mesh.
  19774. * 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.
  19775. * Please consider using the same method from the MeshBuilder class instead.
  19776. *
  19777. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19778. * 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
  19779. * extruded along the Z axis.
  19780. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19781. * 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.
  19782. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19783. * 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
  19784. * 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
  19785. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19789. */
  19790. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  19791. var options = {
  19792. shape: shape,
  19793. path: path,
  19794. scale: scale,
  19795. rotation: rotation,
  19796. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19797. sideOrientation: sideOrientation,
  19798. instance: instance,
  19799. updatable: updatable
  19800. };
  19801. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  19802. };
  19803. /**
  19804. * Creates an custom extruded shape mesh.
  19805. * 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.
  19806. * Please consider using the same method from the MeshBuilder class instead.
  19807. *
  19808. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19809. * 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
  19810. * extruded along the Z axis.
  19811. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19812. * 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
  19813. * and the distance of this point from the begining of the path :
  19814. * ```javascript
  19815. * var rotationFunction = function(i, distance) {
  19816. * // do things
  19817. * return rotationValue; }
  19818. * ```
  19819. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19820. * 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
  19821. * and the distance of this point from the begining of the path :
  19822. * ```javascript
  19823. * var scaleFunction = function(i, distance) {
  19824. * // do things
  19825. * return scaleValue;}
  19826. * ```
  19827. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19828. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19829. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19830. * 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
  19831. * 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
  19832. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19833. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19834. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19835. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19836. */
  19837. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  19838. var options = {
  19839. shape: shape,
  19840. path: path,
  19841. scaleFunction: scaleFunction,
  19842. rotationFunction: rotationFunction,
  19843. ribbonCloseArray: ribbonCloseArray,
  19844. ribbonClosePath: ribbonClosePath,
  19845. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  19846. sideOrientation: sideOrientation,
  19847. instance: instance,
  19848. updatable: updatable
  19849. };
  19850. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  19851. };
  19852. /**
  19853. * Creates lathe mesh.
  19854. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19855. * Please consider using the same method from the MeshBuilder class instead.
  19856. * 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
  19857. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19858. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19859. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19863. */
  19864. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  19865. var options = {
  19866. shape: shape,
  19867. radius: radius,
  19868. tessellation: tessellation,
  19869. sideOrientation: sideOrientation,
  19870. updatable: updatable
  19871. };
  19872. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  19873. };
  19874. /**
  19875. * Creates a plane mesh.
  19876. * Please consider using the same method from the MeshBuilder class instead.
  19877. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19881. */
  19882. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  19883. var options = {
  19884. size: size,
  19885. width: size,
  19886. height: size,
  19887. sideOrientation: sideOrientation,
  19888. updatable: updatable
  19889. };
  19890. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  19891. };
  19892. /**
  19893. * Creates a ground mesh.
  19894. * Please consider using the same method from the MeshBuilder class instead.
  19895. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19896. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19898. */
  19899. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  19900. var options = {
  19901. width: width,
  19902. height: height,
  19903. subdivisions: subdivisions,
  19904. updatable: updatable
  19905. };
  19906. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  19907. };
  19908. /**
  19909. * Creates a tiled ground mesh.
  19910. * Please consider using the same method from the MeshBuilder class instead.
  19911. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19912. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19913. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19914. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19915. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19916. * numbers of subdivisions on the ground width and height of each tile.
  19917. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19918. */
  19919. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  19920. var options = {
  19921. xmin: xmin,
  19922. zmin: zmin,
  19923. xmax: xmax,
  19924. zmax: zmax,
  19925. subdivisions: subdivisions,
  19926. precision: precision,
  19927. updatable: updatable
  19928. };
  19929. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  19930. };
  19931. /**
  19932. * Creates a ground mesh from a height map.
  19933. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19934. * Please consider using the same method from the MeshBuilder class instead.
  19935. * The parameter `url` sets the URL of the height map image resource.
  19936. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19937. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19938. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19939. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19940. * 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).
  19941. * This function is passed the newly built mesh :
  19942. * ```javascript
  19943. * function(mesh) { // do things
  19944. * return; }
  19945. * ```
  19946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19947. */
  19948. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  19949. var options = {
  19950. width: width,
  19951. height: height,
  19952. subdivisions: subdivisions,
  19953. minHeight: minHeight,
  19954. maxHeight: maxHeight,
  19955. updatable: updatable,
  19956. onReady: onReady
  19957. };
  19958. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  19959. };
  19960. /**
  19961. * Creates a tube mesh.
  19962. * 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.
  19963. * Please consider using the same method from the MeshBuilder class instead.
  19964. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  19965. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19966. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19967. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19968. * 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.
  19969. * It must return a radius value (positive float) :
  19970. * ```javascript
  19971. * var radiusFunction = function(i, distance) {
  19972. * // do things
  19973. * return radius; }
  19974. * ```
  19975. * 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
  19976. * 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
  19977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19978. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19980. */
  19981. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  19982. var options = {
  19983. path: path,
  19984. radius: radius,
  19985. tessellation: tessellation,
  19986. radiusFunction: radiusFunction,
  19987. arc: 1,
  19988. cap: cap,
  19989. updatable: updatable,
  19990. sideOrientation: sideOrientation,
  19991. instance: instance
  19992. };
  19993. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  19994. };
  19995. /**
  19996. * Creates a polyhedron mesh.
  19997. * Please consider using the same method from the MeshBuilder class instead.
  19998. * 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
  19999. * to choose the wanted type.
  20000. * The parameter `size` (positive float, default 1) sets the polygon size.
  20001. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20002. * 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`.
  20003. * 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
  20004. * 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)`).
  20005. * 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
  20006. * 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.
  20007. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20008. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20009. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20010. */
  20011. Mesh.CreatePolyhedron = function (name, options, scene) {
  20012. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20013. };
  20014. /**
  20015. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20016. * Please consider using the same method from the MeshBuilder class instead.
  20017. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20018. * 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`).
  20019. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20020. * 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.
  20021. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20022. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20024. */
  20025. Mesh.CreateIcoSphere = function (name, options, scene) {
  20026. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20027. };
  20028. /**
  20029. * Creates a decal mesh.
  20030. * Please consider using the same method from the MeshBuilder class instead.
  20031. * 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.
  20032. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20033. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20034. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20035. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20036. */
  20037. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20038. var options = {
  20039. position: position,
  20040. normal: normal,
  20041. size: size,
  20042. angle: angle
  20043. };
  20044. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20045. };
  20046. // Skeletons
  20047. /**
  20048. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20049. */
  20050. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20051. var source;
  20052. if (!this._sourcePositions) {
  20053. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20054. this._sourcePositions = new Float32Array(source);
  20055. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20056. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20057. }
  20058. }
  20059. return this._sourcePositions;
  20060. };
  20061. /**
  20062. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20063. */
  20064. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20065. var source;
  20066. if (!this._sourceNormals) {
  20067. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20068. this._sourceNormals = new Float32Array(source);
  20069. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20070. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20071. }
  20072. }
  20073. return this._sourceNormals;
  20074. };
  20075. /**
  20076. * Update the vertex buffers by applying transformation from the bones
  20077. * @param {skeleton} skeleton to apply
  20078. */
  20079. Mesh.prototype.applySkeleton = function (skeleton) {
  20080. if (!this.geometry) {
  20081. return;
  20082. }
  20083. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20084. return;
  20085. }
  20086. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20087. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20088. return this;
  20089. }
  20090. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20091. return this;
  20092. }
  20093. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20094. return this;
  20095. }
  20096. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20097. return this;
  20098. }
  20099. if (!this._sourcePositions) {
  20100. this.setPositionsForCPUSkinning();
  20101. }
  20102. if (!this._sourceNormals) {
  20103. this.setNormalsForCPUSkinning();
  20104. }
  20105. // positionsData checks for not being Float32Array will only pass at most once
  20106. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20107. if (!(positionsData instanceof Float32Array)) {
  20108. positionsData = new Float32Array(positionsData);
  20109. }
  20110. // normalsData checks for not being Float32Array will only pass at most once
  20111. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20112. if (!(normalsData instanceof Float32Array)) {
  20113. normalsData = new Float32Array(normalsData);
  20114. }
  20115. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20116. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20117. var needExtras = this.numBoneInfluencers > 4;
  20118. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20119. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20120. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20121. var tempVector3 = BABYLON.Vector3.Zero();
  20122. var finalMatrix = new BABYLON.Matrix();
  20123. var tempMatrix = new BABYLON.Matrix();
  20124. var matWeightIdx = 0;
  20125. var inf;
  20126. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20127. var weight;
  20128. for (inf = 0; inf < 4; inf++) {
  20129. weight = matricesWeightsData[matWeightIdx + inf];
  20130. if (weight > 0) {
  20131. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20132. finalMatrix.addToSelf(tempMatrix);
  20133. }
  20134. else
  20135. break;
  20136. }
  20137. if (needExtras) {
  20138. for (inf = 0; inf < 4; inf++) {
  20139. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20140. if (weight > 0) {
  20141. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20142. finalMatrix.addToSelf(tempMatrix);
  20143. }
  20144. else
  20145. break;
  20146. }
  20147. }
  20148. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20149. tempVector3.toArray(positionsData, index);
  20150. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20151. tempVector3.toArray(normalsData, index);
  20152. finalMatrix.reset();
  20153. }
  20154. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20155. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20156. return this;
  20157. };
  20158. // Tools
  20159. /**
  20160. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20161. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20162. */
  20163. Mesh.MinMax = function (meshes) {
  20164. var minVector = null;
  20165. var maxVector = null;
  20166. for (var i in meshes) {
  20167. var mesh = meshes[i];
  20168. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20169. if (!minVector) {
  20170. minVector = boundingBox.minimumWorld;
  20171. maxVector = boundingBox.maximumWorld;
  20172. continue;
  20173. }
  20174. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20175. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20176. }
  20177. return {
  20178. min: minVector,
  20179. max: maxVector
  20180. };
  20181. };
  20182. /**
  20183. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20184. */
  20185. Mesh.Center = function (meshesOrMinMaxVector) {
  20186. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20187. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20188. };
  20189. /**
  20190. * Merge the array of meshes into a single mesh for performance reasons.
  20191. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20192. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20193. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20194. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20195. */
  20196. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20197. if (disposeSource === void 0) { disposeSource = true; }
  20198. var index;
  20199. if (!allow32BitsIndices) {
  20200. var totalVertices = 0;
  20201. // Counting vertices
  20202. for (index = 0; index < meshes.length; index++) {
  20203. if (meshes[index]) {
  20204. totalVertices += meshes[index].getTotalVertices();
  20205. if (totalVertices > 65536) {
  20206. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20207. return null;
  20208. }
  20209. }
  20210. }
  20211. }
  20212. // Merge
  20213. var vertexData;
  20214. var otherVertexData;
  20215. var source;
  20216. for (index = 0; index < meshes.length; index++) {
  20217. if (meshes[index]) {
  20218. meshes[index].computeWorldMatrix(true);
  20219. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20220. otherVertexData.transform(meshes[index].getWorldMatrix());
  20221. if (vertexData) {
  20222. vertexData.merge(otherVertexData);
  20223. }
  20224. else {
  20225. vertexData = otherVertexData;
  20226. source = meshes[index];
  20227. }
  20228. }
  20229. }
  20230. if (!meshSubclass) {
  20231. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20232. }
  20233. vertexData.applyToMesh(meshSubclass);
  20234. // Setting properties
  20235. meshSubclass.material = source.material;
  20236. meshSubclass.checkCollisions = source.checkCollisions;
  20237. // Cleaning
  20238. if (disposeSource) {
  20239. for (index = 0; index < meshes.length; index++) {
  20240. if (meshes[index]) {
  20241. meshes[index].dispose();
  20242. }
  20243. }
  20244. }
  20245. return meshSubclass;
  20246. };
  20247. // Consts
  20248. Mesh._FRONTSIDE = 0;
  20249. Mesh._BACKSIDE = 1;
  20250. Mesh._DOUBLESIDE = 2;
  20251. Mesh._DEFAULTSIDE = 0;
  20252. Mesh._NO_CAP = 0;
  20253. Mesh._CAP_START = 1;
  20254. Mesh._CAP_END = 2;
  20255. Mesh._CAP_ALL = 3;
  20256. return Mesh;
  20257. })(BABYLON.AbstractMesh);
  20258. BABYLON.Mesh = Mesh;
  20259. })(BABYLON || (BABYLON = {}));
  20260. var BABYLON;
  20261. (function (BABYLON) {
  20262. var SubMesh = (function () {
  20263. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20264. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20265. this.materialIndex = materialIndex;
  20266. this.verticesStart = verticesStart;
  20267. this.verticesCount = verticesCount;
  20268. this.indexStart = indexStart;
  20269. this.indexCount = indexCount;
  20270. this._renderId = 0;
  20271. this._mesh = mesh;
  20272. this._renderingMesh = renderingMesh || mesh;
  20273. mesh.subMeshes.push(this);
  20274. this._trianglePlanes = [];
  20275. this._id = mesh.subMeshes.length - 1;
  20276. if (createBoundingBox) {
  20277. this.refreshBoundingInfo();
  20278. mesh.computeWorldMatrix(true);
  20279. }
  20280. }
  20281. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20282. get: function () {
  20283. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20284. },
  20285. enumerable: true,
  20286. configurable: true
  20287. });
  20288. SubMesh.prototype.getBoundingInfo = function () {
  20289. if (this.IsGlobal) {
  20290. return this._mesh.getBoundingInfo();
  20291. }
  20292. return this._boundingInfo;
  20293. };
  20294. SubMesh.prototype.getMesh = function () {
  20295. return this._mesh;
  20296. };
  20297. SubMesh.prototype.getRenderingMesh = function () {
  20298. return this._renderingMesh;
  20299. };
  20300. SubMesh.prototype.getMaterial = function () {
  20301. var rootMaterial = this._renderingMesh.material;
  20302. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20303. var multiMaterial = rootMaterial;
  20304. return multiMaterial.getSubMaterial(this.materialIndex);
  20305. }
  20306. if (!rootMaterial) {
  20307. return this._mesh.getScene().defaultMaterial;
  20308. }
  20309. return rootMaterial;
  20310. };
  20311. // Methods
  20312. SubMesh.prototype.refreshBoundingInfo = function () {
  20313. this._lastColliderWorldVertices = null;
  20314. if (this.IsGlobal) {
  20315. return;
  20316. }
  20317. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20318. if (!data) {
  20319. this._boundingInfo = this._mesh._boundingInfo;
  20320. return;
  20321. }
  20322. var indices = this._renderingMesh.getIndices();
  20323. var extend;
  20324. //is this the only submesh?
  20325. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20326. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20327. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20328. }
  20329. else {
  20330. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20331. }
  20332. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20333. };
  20334. SubMesh.prototype._checkCollision = function (collider) {
  20335. return this.getBoundingInfo()._checkCollision(collider);
  20336. };
  20337. SubMesh.prototype.updateBoundingInfo = function (world) {
  20338. if (!this.getBoundingInfo()) {
  20339. this.refreshBoundingInfo();
  20340. }
  20341. this.getBoundingInfo().update(world);
  20342. };
  20343. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20344. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20345. };
  20346. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20347. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20348. };
  20349. SubMesh.prototype.render = function (enableAlphaMode) {
  20350. this._renderingMesh.render(this, enableAlphaMode);
  20351. };
  20352. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20353. if (!this._linesIndexBuffer) {
  20354. var linesIndices = [];
  20355. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20356. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20357. }
  20358. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20359. this.linesIndexCount = linesIndices.length;
  20360. }
  20361. return this._linesIndexBuffer;
  20362. };
  20363. SubMesh.prototype.canIntersects = function (ray) {
  20364. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20365. };
  20366. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20367. var intersectInfo = null;
  20368. // LineMesh first as it's also a Mesh...
  20369. if (this._mesh instanceof BABYLON.LinesMesh) {
  20370. var lineMesh = this._mesh;
  20371. // Line test
  20372. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20373. var p0 = positions[indices[index]];
  20374. var p1 = positions[indices[index + 1]];
  20375. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20376. if (length < 0) {
  20377. continue;
  20378. }
  20379. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20380. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20381. if (fastCheck) {
  20382. break;
  20383. }
  20384. }
  20385. }
  20386. }
  20387. else {
  20388. // Triangles test
  20389. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20390. var p0 = positions[indices[index]];
  20391. var p1 = positions[indices[index + 1]];
  20392. var p2 = positions[indices[index + 2]];
  20393. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20394. if (currentIntersectInfo) {
  20395. if (currentIntersectInfo.distance < 0) {
  20396. continue;
  20397. }
  20398. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20399. intersectInfo = currentIntersectInfo;
  20400. intersectInfo.faceId = index / 3;
  20401. if (fastCheck) {
  20402. break;
  20403. }
  20404. }
  20405. }
  20406. }
  20407. }
  20408. return intersectInfo;
  20409. };
  20410. // Clone
  20411. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20412. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20413. if (!this.IsGlobal) {
  20414. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20415. }
  20416. return result;
  20417. };
  20418. // Dispose
  20419. SubMesh.prototype.dispose = function () {
  20420. if (this._linesIndexBuffer) {
  20421. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20422. this._linesIndexBuffer = null;
  20423. }
  20424. // Remove from mesh
  20425. var index = this._mesh.subMeshes.indexOf(this);
  20426. this._mesh.subMeshes.splice(index, 1);
  20427. };
  20428. // Statics
  20429. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20430. var minVertexIndex = Number.MAX_VALUE;
  20431. var maxVertexIndex = -Number.MAX_VALUE;
  20432. renderingMesh = renderingMesh || mesh;
  20433. var indices = renderingMesh.getIndices();
  20434. for (var index = startIndex; index < startIndex + indexCount; index++) {
  20435. var vertexIndex = indices[index];
  20436. if (vertexIndex < minVertexIndex)
  20437. minVertexIndex = vertexIndex;
  20438. if (vertexIndex > maxVertexIndex)
  20439. maxVertexIndex = vertexIndex;
  20440. }
  20441. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  20442. };
  20443. return SubMesh;
  20444. })();
  20445. BABYLON.SubMesh = SubMesh;
  20446. })(BABYLON || (BABYLON = {}));
  20447. var BABYLON;
  20448. (function (BABYLON) {
  20449. var MeshBuilder = (function () {
  20450. function MeshBuilder() {
  20451. }
  20452. /**
  20453. * Creates a box mesh.
  20454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  20455. * The parameter `size` sets the size (float) of each box side (default 1).
  20456. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  20457. * 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).
  20458. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  20459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20462. */
  20463. MeshBuilder.CreateBox = function (name, options, scene) {
  20464. var box = new BABYLON.Mesh(name, scene);
  20465. var vertexData = BABYLON.VertexData.CreateBox(options);
  20466. vertexData.applyToMesh(box, options.updatable);
  20467. return box;
  20468. };
  20469. /**
  20470. * Creates a sphere mesh.
  20471. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  20472. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20473. * 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`).
  20474. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20475. * 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
  20476. * 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).
  20477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20478. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20480. */
  20481. MeshBuilder.CreateSphere = function (name, options, scene) {
  20482. var sphere = new BABYLON.Mesh(name, scene);
  20483. var vertexData = BABYLON.VertexData.CreateSphere(options);
  20484. vertexData.applyToMesh(sphere, options.updatable);
  20485. return sphere;
  20486. };
  20487. /**
  20488. * Creates a plane polygonal mesh. By default, this is a disc.
  20489. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  20490. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20491. * 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.
  20492. * 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
  20493. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20494. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20495. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20496. */
  20497. MeshBuilder.CreateDisc = function (name, options, scene) {
  20498. var disc = new BABYLON.Mesh(name, scene);
  20499. var vertexData = BABYLON.VertexData.CreateDisc(options);
  20500. vertexData.applyToMesh(disc, options.updatable);
  20501. return disc;
  20502. };
  20503. /**
  20504. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20505. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  20506. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20507. * 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`).
  20508. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20509. * 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.
  20510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20513. */
  20514. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  20515. var sphere = new BABYLON.Mesh(name, scene);
  20516. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  20517. vertexData.applyToMesh(sphere, options.updatable);
  20518. return sphere;
  20519. };
  20520. ;
  20521. /**
  20522. * Creates a ribbon mesh.
  20523. * 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.
  20524. *
  20525. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20526. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20527. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20528. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20529. * 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.
  20530. * 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.
  20531. * 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
  20532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20534. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20536. */
  20537. MeshBuilder.CreateRibbon = function (name, options, scene) {
  20538. var pathArray = options.pathArray;
  20539. var closeArray = options.closeArray;
  20540. var closePath = options.closePath;
  20541. var offset = options.offset;
  20542. var sideOrientation = options.sideOrientation;
  20543. var instance = options.instance;
  20544. var updatable = options.updatable;
  20545. if (instance) {
  20546. // positionFunction : ribbon case
  20547. // only pathArray and sideOrientation parameters are taken into account for positions update
  20548. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  20549. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  20550. var positionFunction = function (positions) {
  20551. var minlg = pathArray[0].length;
  20552. var i = 0;
  20553. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  20554. for (var si = 1; si <= ns; si++) {
  20555. for (var p = 0; p < pathArray.length; p++) {
  20556. var path = pathArray[p];
  20557. var l = path.length;
  20558. minlg = (minlg < l) ? minlg : l;
  20559. var j = 0;
  20560. while (j < minlg) {
  20561. positions[i] = path[j].x;
  20562. positions[i + 1] = path[j].y;
  20563. positions[i + 2] = path[j].z;
  20564. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  20565. BABYLON.Tmp.Vector3[0].x = path[j].x;
  20566. }
  20567. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  20568. BABYLON.Tmp.Vector3[1].x = path[j].x;
  20569. }
  20570. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  20571. BABYLON.Tmp.Vector3[0].y = path[j].y;
  20572. }
  20573. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  20574. BABYLON.Tmp.Vector3[1].y = path[j].y;
  20575. }
  20576. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  20577. BABYLON.Tmp.Vector3[0].z = path[j].z;
  20578. }
  20579. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  20580. BABYLON.Tmp.Vector3[1].z = path[j].z;
  20581. }
  20582. j++;
  20583. i += 3;
  20584. }
  20585. if (instance._closePath) {
  20586. positions[i] = path[0].x;
  20587. positions[i + 1] = path[0].y;
  20588. positions[i + 2] = path[0].z;
  20589. i += 3;
  20590. }
  20591. }
  20592. }
  20593. };
  20594. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20595. positionFunction(positions);
  20596. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  20597. instance._boundingInfo.update(instance._worldMatrix);
  20598. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20599. if (!(instance.areNormalsFrozen)) {
  20600. var indices = instance.getIndices();
  20601. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20602. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20603. if (instance._closePath) {
  20604. var indexFirst = 0;
  20605. var indexLast = 0;
  20606. for (var p = 0; p < pathArray.length; p++) {
  20607. indexFirst = instance._idx[p] * 3;
  20608. if (p + 1 < pathArray.length) {
  20609. indexLast = (instance._idx[p + 1] - 1) * 3;
  20610. }
  20611. else {
  20612. indexLast = normals.length - 3;
  20613. }
  20614. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  20615. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  20616. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  20617. normals[indexLast] = normals[indexFirst];
  20618. normals[indexLast + 1] = normals[indexFirst + 1];
  20619. normals[indexLast + 2] = normals[indexFirst + 2];
  20620. }
  20621. }
  20622. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20623. }
  20624. return instance;
  20625. }
  20626. else {
  20627. var ribbon = new BABYLON.Mesh(name, scene);
  20628. ribbon.sideOrientation = sideOrientation;
  20629. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  20630. if (closePath) {
  20631. ribbon._idx = vertexData._idx;
  20632. }
  20633. ribbon._closePath = closePath;
  20634. ribbon._closeArray = closeArray;
  20635. vertexData.applyToMesh(ribbon, updatable);
  20636. return ribbon;
  20637. }
  20638. };
  20639. /**
  20640. * Creates a cylinder or a cone mesh.
  20641. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  20642. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20643. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20644. * 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.
  20645. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20646. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20647. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  20648. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  20649. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  20650. * 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).
  20651. * 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
  20652. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  20653. * 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
  20654. * 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.
  20655. * If `enclose` is false, a ring surface is one element.
  20656. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  20657. * 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
  20658. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20659. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20661. */
  20662. MeshBuilder.CreateCylinder = function (name, options, scene) {
  20663. var cylinder = new BABYLON.Mesh(name, scene);
  20664. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  20665. vertexData.applyToMesh(cylinder, options.updatable);
  20666. return cylinder;
  20667. };
  20668. /**
  20669. * Creates a torus mesh.
  20670. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  20671. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20672. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20673. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20677. */
  20678. MeshBuilder.CreateTorus = function (name, options, scene) {
  20679. var torus = new BABYLON.Mesh(name, scene);
  20680. var vertexData = BABYLON.VertexData.CreateTorus(options);
  20681. vertexData.applyToMesh(torus, options.updatable);
  20682. return torus;
  20683. };
  20684. /**
  20685. * Creates a torus knot mesh.
  20686. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  20687. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20688. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20689. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20690. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  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 mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20694. */
  20695. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  20696. var torusKnot = new BABYLON.Mesh(name, scene);
  20697. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  20698. vertexData.applyToMesh(torusKnot, options.updatable);
  20699. return torusKnot;
  20700. };
  20701. /**
  20702. * Creates a line system mesh.
  20703. * A line system is a pool of many lines gathered in a single mesh.
  20704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  20705. * 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.
  20706. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  20707. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  20708. * 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
  20709. * 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
  20710. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  20711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20712. */
  20713. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  20714. var instance = options.instance;
  20715. var lines = options.lines;
  20716. if (instance) {
  20717. var positionFunction = function (positions) {
  20718. var i = 0;
  20719. for (var l = 0; l < lines.length; l++) {
  20720. var points = lines[l];
  20721. for (var p = 0; p < points.length; p++) {
  20722. positions[i] = points[p].x;
  20723. positions[i + 1] = points[p].y;
  20724. positions[i + 2] = points[p].z;
  20725. i += 3;
  20726. }
  20727. }
  20728. };
  20729. instance.updateMeshPositions(positionFunction, false);
  20730. return instance;
  20731. }
  20732. // line system creation
  20733. var lineSystem = new BABYLON.LinesMesh(name, scene);
  20734. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  20735. vertexData.applyToMesh(lineSystem, options.updatable);
  20736. return lineSystem;
  20737. };
  20738. /**
  20739. * Creates a line mesh.
  20740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  20741. * 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.
  20742. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20743. * The parameter `points` is an array successive Vector3.
  20744. * 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
  20745. * When updating an instance, remember that only point positions can change, not the number of points.
  20746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20747. */
  20748. MeshBuilder.CreateLines = function (name, options, scene) {
  20749. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  20750. return lines;
  20751. };
  20752. /**
  20753. * Creates a dashed line mesh.
  20754. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  20755. * 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.
  20756. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20757. * The parameter `points` is an array successive Vector3.
  20758. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20759. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20760. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20761. * 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
  20762. * When updating an instance, remember that only point positions can change, not the number of points.
  20763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20764. */
  20765. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  20766. var points = options.points;
  20767. var instance = options.instance;
  20768. var gapSize = options.gapSize;
  20769. var dashNb = options.dashNb;
  20770. var dashSize = options.dashSize;
  20771. if (instance) {
  20772. var positionFunction = function (positions) {
  20773. var curvect = BABYLON.Vector3.Zero();
  20774. var nbSeg = positions.length / 6;
  20775. var lg = 0;
  20776. var nb = 0;
  20777. var shft = 0;
  20778. var dashshft = 0;
  20779. var curshft = 0;
  20780. var p = 0;
  20781. var i = 0;
  20782. var j = 0;
  20783. for (i = 0; i < points.length - 1; i++) {
  20784. points[i + 1].subtractToRef(points[i], curvect);
  20785. lg += curvect.length();
  20786. }
  20787. shft = lg / nbSeg;
  20788. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  20789. for (i = 0; i < points.length - 1; i++) {
  20790. points[i + 1].subtractToRef(points[i], curvect);
  20791. nb = Math.floor(curvect.length() / shft);
  20792. curvect.normalize();
  20793. j = 0;
  20794. while (j < nb && p < positions.length) {
  20795. curshft = shft * j;
  20796. positions[p] = points[i].x + curshft * curvect.x;
  20797. positions[p + 1] = points[i].y + curshft * curvect.y;
  20798. positions[p + 2] = points[i].z + curshft * curvect.z;
  20799. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  20800. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  20801. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  20802. p += 6;
  20803. j++;
  20804. }
  20805. }
  20806. while (p < positions.length) {
  20807. positions[p] = points[i].x;
  20808. positions[p + 1] = points[i].y;
  20809. positions[p + 2] = points[i].z;
  20810. p += 3;
  20811. }
  20812. };
  20813. instance.updateMeshPositions(positionFunction, false);
  20814. return instance;
  20815. }
  20816. // dashed lines creation
  20817. var dashedLines = new BABYLON.LinesMesh(name, scene);
  20818. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  20819. vertexData.applyToMesh(dashedLines, options.updatable);
  20820. dashedLines.dashSize = dashSize;
  20821. dashedLines.gapSize = gapSize;
  20822. return dashedLines;
  20823. };
  20824. /**
  20825. * Creates an extruded shape mesh.
  20826. * 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.
  20827. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  20828. *
  20829. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20830. * 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
  20831. * extruded along the Z axis.
  20832. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20833. * 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.
  20834. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20835. * 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
  20836. * 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
  20837. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20840. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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.ExtrudeShape = function (name, options, scene) {
  20844. var path = options.path;
  20845. var shape = options.shape;
  20846. var scale = options.scale || 1;
  20847. var rotation = options.rotation || 0;
  20848. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20849. var updatable = options.updatable;
  20850. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20851. var instance = options.instance;
  20852. var invertUV = options.invertUV || false;
  20853. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  20854. };
  20855. /**
  20856. * Creates an custom extruded shape mesh.
  20857. * 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.
  20858. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  20859. *
  20860. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20861. * 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
  20862. * extruded along the Z axis.
  20863. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20864. * 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
  20865. * and the distance of this point from the begining of the path :
  20866. * ```javascript
  20867. * var rotationFunction = function(i, distance) {
  20868. * // do things
  20869. * return rotationValue; }
  20870. * ```
  20871. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20872. * 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
  20873. * and the distance of this point from the begining of the path :
  20874. * ```javascript
  20875. * var scaleFunction = function(i, distance) {
  20876. * // do things
  20877. * return scaleValue;}
  20878. * ```
  20879. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20880. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20881. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20882. * 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
  20883. * 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
  20884. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20886. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20887. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20889. */
  20890. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  20891. var path = options.path;
  20892. var shape = options.shape;
  20893. var scaleFunction = options.scaleFunction || (function () { return 1; });
  20894. var rotationFunction = options.rotationFunction || (function () { return 0; });
  20895. var ribbonCloseArray = options.ribbonCloseArray || false;
  20896. var ribbonClosePath = options.ribbonClosePath || false;
  20897. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  20898. var updatable = options.updatable;
  20899. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20900. var instance = options.instance;
  20901. var invertUV = options.invertUV || false;
  20902. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  20903. };
  20904. /**
  20905. * Creates lathe mesh.
  20906. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20907. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  20908. *
  20909. * 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
  20910. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20911. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20912. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20913. * 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.
  20914. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  20915. * 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
  20916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20917. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20918. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  20919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20920. */
  20921. MeshBuilder.CreateLathe = function (name, options, scene) {
  20922. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  20923. var closed = (options.closed === undefined) ? true : options.closed;
  20924. var shape = options.shape;
  20925. var radius = options.radius || 1;
  20926. var tessellation = options.tessellation || 64;
  20927. var updatable = options.updatable;
  20928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  20929. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  20930. var pi2 = Math.PI * 2;
  20931. var paths = new Array();
  20932. var invertUV = options.invertUV || false;
  20933. var i = 0;
  20934. var p = 0;
  20935. var step = pi2 / tessellation * arc;
  20936. var rotated;
  20937. var path = new Array();
  20938. ;
  20939. for (i = 0; i <= tessellation; i++) {
  20940. var path = [];
  20941. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  20942. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  20943. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  20944. }
  20945. for (p = 0; p < shape.length; p++) {
  20946. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  20947. path.push(rotated);
  20948. }
  20949. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  20950. 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));
  20951. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  20952. }
  20953. paths.push(path);
  20954. }
  20955. // lathe ribbon
  20956. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  20957. return lathe;
  20958. };
  20959. /**
  20960. * Creates a plane mesh.
  20961. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20962. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20963. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  20964. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  20965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20968. */
  20969. MeshBuilder.CreatePlane = function (name, options, scene) {
  20970. var plane = new BABYLON.Mesh(name, scene);
  20971. var vertexData = BABYLON.VertexData.CreatePlane(options);
  20972. vertexData.applyToMesh(plane, options.updatable);
  20973. if (options.sourcePlane) {
  20974. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  20975. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  20976. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  20977. plane.rotate(vectorProduct, product);
  20978. }
  20979. return plane;
  20980. };
  20981. /**
  20982. * Creates a ground mesh.
  20983. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  20984. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20985. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20986. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20987. */
  20988. MeshBuilder.CreateGround = function (name, options, scene) {
  20989. var ground = new BABYLON.GroundMesh(name, scene);
  20990. ground._setReady(false);
  20991. ground._subdivisions = options.subdivisions || 1;
  20992. ground._width = options.width || 1;
  20993. ground._height = options.height || 1;
  20994. ground._maxX = ground._width / 2;
  20995. ground._maxZ = ground._height / 2;
  20996. ground._minX = -ground._maxX;
  20997. ground._minZ = -ground._maxZ;
  20998. var vertexData = BABYLON.VertexData.CreateGround(options);
  20999. vertexData.applyToMesh(ground, options.updatable);
  21000. ground._setReady(true);
  21001. return ground;
  21002. };
  21003. /**
  21004. * Creates a tiled ground mesh.
  21005. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21006. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21007. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21008. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21009. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21010. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21011. * numbers of subdivisions on the ground width and height of each tile.
  21012. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21013. */
  21014. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21015. var tiledGround = new BABYLON.Mesh(name, scene);
  21016. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21017. vertexData.applyToMesh(tiledGround, options.updatable);
  21018. return tiledGround;
  21019. };
  21020. /**
  21021. * Creates a ground mesh from a height map.
  21022. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21023. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21024. * The parameter `url` sets the URL of the height map image resource.
  21025. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21026. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21027. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21028. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21029. * 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).
  21030. * This function is passed the newly built mesh :
  21031. * ```javascript
  21032. * function(mesh) { // do things
  21033. * return; }
  21034. * ```
  21035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21036. */
  21037. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21038. var width = options.width || 10.0;
  21039. var height = options.height || 10.0;
  21040. var subdivisions = options.subdivisions || 1 | 0;
  21041. var minHeight = options.minHeight || 0.0;
  21042. var maxHeight = options.maxHeight || 10.0;
  21043. var updatable = options.updatable;
  21044. var onReady = options.onReady;
  21045. var ground = new BABYLON.GroundMesh(name, scene);
  21046. ground._subdivisions = subdivisions;
  21047. ground._width = width;
  21048. ground._height = height;
  21049. ground._maxX = ground._width / 2.0;
  21050. ground._maxZ = ground._height / 2.0;
  21051. ground._minX = -ground._maxX;
  21052. ground._minZ = -ground._maxZ;
  21053. ground._setReady(false);
  21054. var onload = function (img) {
  21055. // Getting height map data
  21056. var canvas = document.createElement("canvas");
  21057. var context = canvas.getContext("2d");
  21058. var bufferWidth = img.width;
  21059. var bufferHeight = img.height;
  21060. canvas.width = bufferWidth;
  21061. canvas.height = bufferHeight;
  21062. context.drawImage(img, 0, 0);
  21063. // Create VertexData from map data
  21064. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21065. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21066. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21067. width: width, height: height,
  21068. subdivisions: subdivisions,
  21069. minHeight: minHeight, maxHeight: maxHeight,
  21070. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21071. });
  21072. vertexData.applyToMesh(ground, updatable);
  21073. ground._setReady(true);
  21074. //execute ready callback, if set
  21075. if (onReady) {
  21076. onReady(ground);
  21077. }
  21078. };
  21079. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21080. return ground;
  21081. };
  21082. /**
  21083. * Creates a tube mesh.
  21084. * 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.
  21085. *
  21086. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21087. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21088. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21089. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21090. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21091. * 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.
  21092. * It must return a radius value (positive float) :
  21093. * ```javascript
  21094. * var radiusFunction = function(i, distance) {
  21095. * // do things
  21096. * return radius; }
  21097. * ```
  21098. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21099. * 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
  21100. * 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
  21101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21103. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21105. */
  21106. MeshBuilder.CreateTube = function (name, options, scene) {
  21107. var path = options.path;
  21108. var radius = options.radius || 1.0;
  21109. var tessellation = options.tessellation || 64 | 0;
  21110. var radiusFunction = options.radiusFunction;
  21111. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21112. var invertUV = options.invertUV || false;
  21113. var updatable = options.updatable;
  21114. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21115. var instance = options.instance;
  21116. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21117. // tube geometry
  21118. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21119. var tangents = path3D.getTangents();
  21120. var normals = path3D.getNormals();
  21121. var distances = path3D.getDistances();
  21122. var pi2 = Math.PI * 2;
  21123. var step = pi2 / tessellation * arc;
  21124. var returnRadius = function () { return radius; };
  21125. var radiusFunctionFinal = radiusFunction || returnRadius;
  21126. var circlePath;
  21127. var rad;
  21128. var normal;
  21129. var rotated;
  21130. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21131. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21132. for (var i = 0; i < path.length; i++) {
  21133. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21134. circlePath = Array(); // current circle array
  21135. normal = normals[i]; // current normal
  21136. for (var t = 0; t < tessellation; t++) {
  21137. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21138. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21139. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21140. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21141. circlePath[t] = rotated;
  21142. }
  21143. circlePaths[index] = circlePath;
  21144. index++;
  21145. }
  21146. // cap
  21147. var capPath = function (nbPoints, pathIndex) {
  21148. var pointCap = Array();
  21149. for (var i = 0; i < nbPoints; i++) {
  21150. pointCap.push(path[pathIndex]);
  21151. }
  21152. return pointCap;
  21153. };
  21154. switch (cap) {
  21155. case BABYLON.Mesh.NO_CAP:
  21156. break;
  21157. case BABYLON.Mesh.CAP_START:
  21158. circlePaths[0] = capPath(tessellation, 0);
  21159. circlePaths[1] = circlePaths[2].slice(0);
  21160. break;
  21161. case BABYLON.Mesh.CAP_END:
  21162. circlePaths[index] = circlePaths[index - 1].slice(0);
  21163. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21164. break;
  21165. case BABYLON.Mesh.CAP_ALL:
  21166. circlePaths[0] = capPath(tessellation, 0);
  21167. circlePaths[1] = circlePaths[2].slice(0);
  21168. circlePaths[index] = circlePaths[index - 1].slice(0);
  21169. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21170. break;
  21171. default:
  21172. break;
  21173. }
  21174. return circlePaths;
  21175. };
  21176. var path3D;
  21177. var pathArray;
  21178. if (instance) {
  21179. var arc = options.arc || instance.arc;
  21180. path3D = (instance.path3D).update(path);
  21181. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21182. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21183. instance.path3D = path3D;
  21184. instance.pathArray = pathArray;
  21185. instance.arc = arc;
  21186. return instance;
  21187. }
  21188. // tube creation
  21189. path3D = new BABYLON.Path3D(path);
  21190. var newPathArray = new Array();
  21191. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21192. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21193. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21194. tube.pathArray = pathArray;
  21195. tube.path3D = path3D;
  21196. tube.tessellation = tessellation;
  21197. tube.cap = cap;
  21198. tube.arc = options.arc;
  21199. return tube;
  21200. };
  21201. /**
  21202. * Creates a polyhedron mesh.
  21203. *
  21204. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21205. * 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
  21206. * to choose the wanted type.
  21207. * The parameter `size` (positive float, default 1) sets the polygon size.
  21208. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21209. * 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`.
  21210. * 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
  21211. * 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)`).
  21212. * 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
  21213. * 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.
  21214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21215. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21217. */
  21218. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21219. var polyhedron = new BABYLON.Mesh(name, scene);
  21220. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21221. vertexData.applyToMesh(polyhedron, options.updatable);
  21222. return polyhedron;
  21223. };
  21224. /**
  21225. * Creates a decal mesh.
  21226. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21227. * 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.
  21228. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21229. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21230. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21231. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21232. */
  21233. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21234. var indices = sourceMesh.getIndices();
  21235. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21236. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21237. var position = options.position || BABYLON.Vector3.Zero();
  21238. var normal = options.normal || BABYLON.Vector3.Up();
  21239. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21240. var angle = options.angle || 0;
  21241. // Getting correct rotation
  21242. if (!normal) {
  21243. var target = new BABYLON.Vector3(0, 0, 1);
  21244. var camera = sourceMesh.getScene().activeCamera;
  21245. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21246. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21247. }
  21248. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21249. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21250. var pitch = Math.atan2(normal.y, len);
  21251. // Matrix
  21252. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21253. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21254. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21255. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21256. var vertexData = new BABYLON.VertexData();
  21257. vertexData.indices = [];
  21258. vertexData.positions = [];
  21259. vertexData.normals = [];
  21260. vertexData.uvs = [];
  21261. var currentVertexDataIndex = 0;
  21262. var extractDecalVector3 = function (indexId) {
  21263. var vertexId = indices[indexId];
  21264. var result = new BABYLON.PositionNormalVertex();
  21265. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21266. // Send vector to decal local world
  21267. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21268. // Get normal
  21269. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21270. return result;
  21271. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21272. var clip = function (vertices, axis) {
  21273. if (vertices.length === 0) {
  21274. return vertices;
  21275. }
  21276. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21277. var clipVertices = function (v0, v1) {
  21278. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21279. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21280. };
  21281. var result = new Array();
  21282. for (var index = 0; index < vertices.length; index += 3) {
  21283. var v1Out;
  21284. var v2Out;
  21285. var v3Out;
  21286. var total = 0;
  21287. var nV1, nV2, nV3, nV4;
  21288. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21289. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21290. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21291. v1Out = d1 > 0;
  21292. v2Out = d2 > 0;
  21293. v3Out = d3 > 0;
  21294. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21295. switch (total) {
  21296. case 0:
  21297. result.push(vertices[index]);
  21298. result.push(vertices[index + 1]);
  21299. result.push(vertices[index + 2]);
  21300. break;
  21301. case 1:
  21302. if (v1Out) {
  21303. nV1 = vertices[index + 1];
  21304. nV2 = vertices[index + 2];
  21305. nV3 = clipVertices(vertices[index], nV1);
  21306. nV4 = clipVertices(vertices[index], nV2);
  21307. }
  21308. if (v2Out) {
  21309. nV1 = vertices[index];
  21310. nV2 = vertices[index + 2];
  21311. nV3 = clipVertices(vertices[index + 1], nV1);
  21312. nV4 = clipVertices(vertices[index + 1], nV2);
  21313. result.push(nV3);
  21314. result.push(nV2.clone());
  21315. result.push(nV1.clone());
  21316. result.push(nV2.clone());
  21317. result.push(nV3.clone());
  21318. result.push(nV4);
  21319. break;
  21320. }
  21321. if (v3Out) {
  21322. nV1 = vertices[index];
  21323. nV2 = vertices[index + 1];
  21324. nV3 = clipVertices(vertices[index + 2], nV1);
  21325. nV4 = clipVertices(vertices[index + 2], nV2);
  21326. }
  21327. result.push(nV1.clone());
  21328. result.push(nV2.clone());
  21329. result.push(nV3);
  21330. result.push(nV4);
  21331. result.push(nV3.clone());
  21332. result.push(nV2.clone());
  21333. break;
  21334. case 2:
  21335. if (!v1Out) {
  21336. nV1 = vertices[index].clone();
  21337. nV2 = clipVertices(nV1, vertices[index + 1]);
  21338. nV3 = clipVertices(nV1, vertices[index + 2]);
  21339. result.push(nV1);
  21340. result.push(nV2);
  21341. result.push(nV3);
  21342. }
  21343. if (!v2Out) {
  21344. nV1 = vertices[index + 1].clone();
  21345. nV2 = clipVertices(nV1, vertices[index + 2]);
  21346. nV3 = clipVertices(nV1, vertices[index]);
  21347. result.push(nV1);
  21348. result.push(nV2);
  21349. result.push(nV3);
  21350. }
  21351. if (!v3Out) {
  21352. nV1 = vertices[index + 2].clone();
  21353. nV2 = clipVertices(nV1, vertices[index]);
  21354. nV3 = clipVertices(nV1, vertices[index + 1]);
  21355. result.push(nV1);
  21356. result.push(nV2);
  21357. result.push(nV3);
  21358. }
  21359. break;
  21360. case 3:
  21361. break;
  21362. }
  21363. }
  21364. return result;
  21365. };
  21366. for (var index = 0; index < indices.length; index += 3) {
  21367. var faceVertices = new Array();
  21368. faceVertices.push(extractDecalVector3(index));
  21369. faceVertices.push(extractDecalVector3(index + 1));
  21370. faceVertices.push(extractDecalVector3(index + 2));
  21371. // Clip
  21372. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21373. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21374. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21375. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21376. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21377. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21378. if (faceVertices.length === 0) {
  21379. continue;
  21380. }
  21381. // Add UVs and get back to world
  21382. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21383. var vertex = faceVertices[vIndex];
  21384. //TODO check for Int32Array
  21385. vertexData.indices.push(currentVertexDataIndex);
  21386. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21387. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21388. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21389. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21390. currentVertexDataIndex++;
  21391. }
  21392. }
  21393. // Return mesh
  21394. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21395. vertexData.applyToMesh(decal);
  21396. decal.position = position.clone();
  21397. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21398. return decal;
  21399. };
  21400. // Privates
  21401. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21402. // extrusion geometry
  21403. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21404. var tangents = path3D.getTangents();
  21405. var normals = path3D.getNormals();
  21406. var binormals = path3D.getBinormals();
  21407. var distances = path3D.getDistances();
  21408. var angle = 0;
  21409. var returnScale = function () { return scale; };
  21410. var returnRotation = function () { return rotation; };
  21411. var rotate = custom ? rotateFunction : returnRotation;
  21412. var scl = custom ? scaleFunction : returnScale;
  21413. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21414. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21415. for (var i = 0; i < curve.length; i++) {
  21416. var shapePath = new Array();
  21417. var angleStep = rotate(i, distances[i]);
  21418. var scaleRatio = scl(i, distances[i]);
  21419. for (var p = 0; p < shape.length; p++) {
  21420. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21421. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21422. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21423. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21424. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21425. shapePath[p] = rotated;
  21426. }
  21427. shapePaths[index] = shapePath;
  21428. angle += angleStep;
  21429. index++;
  21430. }
  21431. // cap
  21432. var capPath = function (shapePath) {
  21433. var pointCap = Array();
  21434. var barycenter = BABYLON.Vector3.Zero();
  21435. var i;
  21436. for (i = 0; i < shapePath.length; i++) {
  21437. barycenter.addInPlace(shapePath[i]);
  21438. }
  21439. barycenter.scaleInPlace(1 / shapePath.length);
  21440. for (i = 0; i < shapePath.length; i++) {
  21441. pointCap.push(barycenter);
  21442. }
  21443. return pointCap;
  21444. };
  21445. switch (cap) {
  21446. case BABYLON.Mesh.NO_CAP:
  21447. break;
  21448. case BABYLON.Mesh.CAP_START:
  21449. shapePaths[0] = capPath(shapePaths[2]);
  21450. shapePaths[1] = shapePaths[2].slice(0);
  21451. break;
  21452. case BABYLON.Mesh.CAP_END:
  21453. shapePaths[index] = shapePaths[index - 1];
  21454. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21455. break;
  21456. case BABYLON.Mesh.CAP_ALL:
  21457. shapePaths[0] = capPath(shapePaths[2]);
  21458. shapePaths[1] = shapePaths[2].slice(0);
  21459. shapePaths[index] = shapePaths[index - 1];
  21460. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  21461. break;
  21462. default:
  21463. break;
  21464. }
  21465. return shapePaths;
  21466. };
  21467. var path3D;
  21468. var pathArray;
  21469. if (instance) {
  21470. path3D = (instance.path3D).update(curve);
  21471. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  21472. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  21473. return instance;
  21474. }
  21475. // extruded shape creation
  21476. path3D = new BABYLON.Path3D(curve);
  21477. var newShapePaths = new Array();
  21478. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21479. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  21480. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  21481. extrudedGeneric.pathArray = pathArray;
  21482. extrudedGeneric.path3D = path3D;
  21483. extrudedGeneric.cap = cap;
  21484. return extrudedGeneric;
  21485. };
  21486. return MeshBuilder;
  21487. })();
  21488. BABYLON.MeshBuilder = MeshBuilder;
  21489. })(BABYLON || (BABYLON = {}));
  21490. var BABYLON;
  21491. (function (BABYLON) {
  21492. var BaseTexture = (function () {
  21493. function BaseTexture(scene) {
  21494. this.hasAlpha = false;
  21495. this.getAlphaFromRGB = false;
  21496. this.level = 1;
  21497. this.coordinatesIndex = 0;
  21498. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21499. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21500. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21501. this.anisotropicFilteringLevel = 4;
  21502. this.isCube = false;
  21503. this.isRenderTarget = false;
  21504. this.animations = new Array();
  21505. /**
  21506. * An event triggered when the texture is disposed.
  21507. * @type {BABYLON.Observable}
  21508. */
  21509. this.onDisposeObservable = new BABYLON.Observable();
  21510. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21511. this._scene = scene;
  21512. this._scene.textures.push(this);
  21513. }
  21514. BaseTexture.prototype.toString = function () {
  21515. return this.name;
  21516. };
  21517. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21518. set: function (callback) {
  21519. if (this._onDisposeObserver) {
  21520. this.onDisposeObservable.remove(this._onDisposeObserver);
  21521. }
  21522. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. BaseTexture.prototype.getScene = function () {
  21528. return this._scene;
  21529. };
  21530. BaseTexture.prototype.getTextureMatrix = function () {
  21531. return null;
  21532. };
  21533. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21534. return null;
  21535. };
  21536. BaseTexture.prototype.getInternalTexture = function () {
  21537. return this._texture;
  21538. };
  21539. BaseTexture.prototype.isReady = function () {
  21540. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21541. return true;
  21542. }
  21543. if (this._texture) {
  21544. return this._texture.isReady;
  21545. }
  21546. return false;
  21547. };
  21548. BaseTexture.prototype.getSize = function () {
  21549. if (this._texture._width) {
  21550. return new BABYLON.Size(this._texture._width, this._texture._height);
  21551. }
  21552. if (this._texture._size) {
  21553. return new BABYLON.Size(this._texture._size, this._texture._size);
  21554. }
  21555. return BABYLON.Size.Zero();
  21556. };
  21557. BaseTexture.prototype.getBaseSize = function () {
  21558. if (!this.isReady() || !this._texture)
  21559. return BABYLON.Size.Zero();
  21560. if (this._texture._size) {
  21561. return new BABYLON.Size(this._texture._size, this._texture._size);
  21562. }
  21563. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  21564. };
  21565. BaseTexture.prototype.scale = function (ratio) {
  21566. };
  21567. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21568. get: function () {
  21569. return false;
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  21575. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21576. for (var index = 0; index < texturesCache.length; index++) {
  21577. var texturesCacheEntry = texturesCache[index];
  21578. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21579. texturesCache.splice(index, 1);
  21580. return;
  21581. }
  21582. }
  21583. };
  21584. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21585. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21586. for (var index = 0; index < texturesCache.length; index++) {
  21587. var texturesCacheEntry = texturesCache[index];
  21588. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  21589. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21590. texturesCacheEntry.references++;
  21591. return texturesCacheEntry;
  21592. }
  21593. }
  21594. }
  21595. return null;
  21596. };
  21597. BaseTexture.prototype.delayLoad = function () {
  21598. };
  21599. BaseTexture.prototype.clone = function () {
  21600. return null;
  21601. };
  21602. BaseTexture.prototype.releaseInternalTexture = function () {
  21603. if (this._texture) {
  21604. this._scene.getEngine().releaseInternalTexture(this._texture);
  21605. delete this._texture;
  21606. }
  21607. };
  21608. BaseTexture.prototype.dispose = function () {
  21609. // Animations
  21610. this.getScene().stopAnimation(this);
  21611. // Remove from scene
  21612. var index = this._scene.textures.indexOf(this);
  21613. if (index >= 0) {
  21614. this._scene.textures.splice(index, 1);
  21615. }
  21616. if (this._texture === undefined) {
  21617. return;
  21618. }
  21619. // Release
  21620. this.releaseInternalTexture();
  21621. // Callback
  21622. this.onDisposeObservable.notifyObservers(this);
  21623. this.onDisposeObservable.clear();
  21624. };
  21625. BaseTexture.prototype.serialize = function () {
  21626. if (!this.name) {
  21627. return null;
  21628. }
  21629. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21630. // Animations
  21631. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21632. return serializationObject;
  21633. };
  21634. __decorate([
  21635. BABYLON.serialize()
  21636. ], BaseTexture.prototype, "name", void 0);
  21637. __decorate([
  21638. BABYLON.serialize()
  21639. ], BaseTexture.prototype, "hasAlpha", void 0);
  21640. __decorate([
  21641. BABYLON.serialize()
  21642. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21643. __decorate([
  21644. BABYLON.serialize()
  21645. ], BaseTexture.prototype, "level", void 0);
  21646. __decorate([
  21647. BABYLON.serialize()
  21648. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21649. __decorate([
  21650. BABYLON.serialize()
  21651. ], BaseTexture.prototype, "coordinatesMode", void 0);
  21652. __decorate([
  21653. BABYLON.serialize()
  21654. ], BaseTexture.prototype, "wrapU", void 0);
  21655. __decorate([
  21656. BABYLON.serialize()
  21657. ], BaseTexture.prototype, "wrapV", void 0);
  21658. __decorate([
  21659. BABYLON.serialize()
  21660. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21661. __decorate([
  21662. BABYLON.serialize()
  21663. ], BaseTexture.prototype, "isCube", void 0);
  21664. __decorate([
  21665. BABYLON.serialize()
  21666. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21667. return BaseTexture;
  21668. })();
  21669. BABYLON.BaseTexture = BaseTexture;
  21670. })(BABYLON || (BABYLON = {}));
  21671. var BABYLON;
  21672. (function (BABYLON) {
  21673. var Texture = (function (_super) {
  21674. __extends(Texture, _super);
  21675. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  21676. var _this = this;
  21677. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21678. if (onLoad === void 0) { onLoad = null; }
  21679. if (onError === void 0) { onError = null; }
  21680. if (buffer === void 0) { buffer = null; }
  21681. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21682. _super.call(this, scene);
  21683. this.uOffset = 0;
  21684. this.vOffset = 0;
  21685. this.uScale = 1.0;
  21686. this.vScale = 1.0;
  21687. this.uAng = 0;
  21688. this.vAng = 0;
  21689. this.wAng = 0;
  21690. this.name = url;
  21691. this.url = url;
  21692. this._noMipmap = noMipmap;
  21693. this._invertY = invertY;
  21694. this._samplingMode = samplingMode;
  21695. this._buffer = buffer;
  21696. this._deleteBuffer = deleteBuffer;
  21697. if (!url) {
  21698. return;
  21699. }
  21700. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  21701. var load = function () {
  21702. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  21703. _this.onLoadObservable.notifyObservers(true);
  21704. }
  21705. if (onLoad) {
  21706. onLoad();
  21707. }
  21708. };
  21709. if (!this._texture) {
  21710. if (!scene.useDelayedTextureLoading) {
  21711. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  21712. if (deleteBuffer) {
  21713. delete this._buffer;
  21714. }
  21715. }
  21716. else {
  21717. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21718. this._delayedOnLoad = load;
  21719. this._delayedOnError = onError;
  21720. }
  21721. }
  21722. else {
  21723. BABYLON.Tools.SetImmediate(function () { return load(); });
  21724. }
  21725. }
  21726. Object.defineProperty(Texture.prototype, "noMipmap", {
  21727. get: function () {
  21728. return this._noMipmap;
  21729. },
  21730. enumerable: true,
  21731. configurable: true
  21732. });
  21733. Texture.prototype.delayLoad = function () {
  21734. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21735. return;
  21736. }
  21737. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21738. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21739. if (!this._texture) {
  21740. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  21741. if (this._deleteBuffer) {
  21742. delete this._buffer;
  21743. }
  21744. }
  21745. };
  21746. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21747. if (!this._texture) {
  21748. return;
  21749. }
  21750. this._samplingMode = samplingMode;
  21751. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21752. };
  21753. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21754. x *= this.uScale;
  21755. y *= this.vScale;
  21756. x -= 0.5 * this.uScale;
  21757. y -= 0.5 * this.vScale;
  21758. z -= 0.5;
  21759. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21760. t.x += 0.5 * this.uScale + this.uOffset;
  21761. t.y += 0.5 * this.vScale + this.vOffset;
  21762. t.z += 0.5;
  21763. };
  21764. Texture.prototype.getTextureMatrix = function () {
  21765. if (this.uOffset === this._cachedUOffset &&
  21766. this.vOffset === this._cachedVOffset &&
  21767. this.uScale === this._cachedUScale &&
  21768. this.vScale === this._cachedVScale &&
  21769. this.uAng === this._cachedUAng &&
  21770. this.vAng === this._cachedVAng &&
  21771. this.wAng === this._cachedWAng) {
  21772. return this._cachedTextureMatrix;
  21773. }
  21774. this._cachedUOffset = this.uOffset;
  21775. this._cachedVOffset = this.vOffset;
  21776. this._cachedUScale = this.uScale;
  21777. this._cachedVScale = this.vScale;
  21778. this._cachedUAng = this.uAng;
  21779. this._cachedVAng = this.vAng;
  21780. this._cachedWAng = this.wAng;
  21781. if (!this._cachedTextureMatrix) {
  21782. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21783. this._rowGenerationMatrix = new BABYLON.Matrix();
  21784. this._t0 = BABYLON.Vector3.Zero();
  21785. this._t1 = BABYLON.Vector3.Zero();
  21786. this._t2 = BABYLON.Vector3.Zero();
  21787. }
  21788. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21789. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21790. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21791. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21792. this._t1.subtractInPlace(this._t0);
  21793. this._t2.subtractInPlace(this._t0);
  21794. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21795. this._cachedTextureMatrix.m[0] = this._t1.x;
  21796. this._cachedTextureMatrix.m[1] = this._t1.y;
  21797. this._cachedTextureMatrix.m[2] = this._t1.z;
  21798. this._cachedTextureMatrix.m[4] = this._t2.x;
  21799. this._cachedTextureMatrix.m[5] = this._t2.y;
  21800. this._cachedTextureMatrix.m[6] = this._t2.z;
  21801. this._cachedTextureMatrix.m[8] = this._t0.x;
  21802. this._cachedTextureMatrix.m[9] = this._t0.y;
  21803. this._cachedTextureMatrix.m[10] = this._t0.z;
  21804. return this._cachedTextureMatrix;
  21805. };
  21806. Texture.prototype.getReflectionTextureMatrix = function () {
  21807. if (this.uOffset === this._cachedUOffset &&
  21808. this.vOffset === this._cachedVOffset &&
  21809. this.uScale === this._cachedUScale &&
  21810. this.vScale === this._cachedVScale &&
  21811. this.coordinatesMode === this._cachedCoordinatesMode) {
  21812. return this._cachedTextureMatrix;
  21813. }
  21814. if (!this._cachedTextureMatrix) {
  21815. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21816. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21817. }
  21818. this._cachedCoordinatesMode = this.coordinatesMode;
  21819. switch (this.coordinatesMode) {
  21820. case Texture.PLANAR_MODE:
  21821. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21822. this._cachedTextureMatrix[0] = this.uScale;
  21823. this._cachedTextureMatrix[5] = this.vScale;
  21824. this._cachedTextureMatrix[12] = this.uOffset;
  21825. this._cachedTextureMatrix[13] = this.vOffset;
  21826. break;
  21827. case Texture.PROJECTION_MODE:
  21828. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21829. this._projectionModeMatrix.m[0] = 0.5;
  21830. this._projectionModeMatrix.m[5] = -0.5;
  21831. this._projectionModeMatrix.m[10] = 0.0;
  21832. this._projectionModeMatrix.m[12] = 0.5;
  21833. this._projectionModeMatrix.m[13] = 0.5;
  21834. this._projectionModeMatrix.m[14] = 1.0;
  21835. this._projectionModeMatrix.m[15] = 1.0;
  21836. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21837. break;
  21838. default:
  21839. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21840. break;
  21841. }
  21842. return this._cachedTextureMatrix;
  21843. };
  21844. Texture.prototype.clone = function () {
  21845. var _this = this;
  21846. return BABYLON.SerializationHelper.Clone(function () {
  21847. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21848. }, this);
  21849. };
  21850. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21851. get: function () {
  21852. if (!this._onLoadObservarble) {
  21853. this._onLoadObservarble = new BABYLON.Observable();
  21854. }
  21855. return this._onLoadObservarble;
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. // Statics
  21861. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  21862. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21863. if (onLoad === void 0) { onLoad = null; }
  21864. if (onError === void 0) { onError = null; }
  21865. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  21866. };
  21867. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21868. if (parsedTexture.isCube) {
  21869. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21870. }
  21871. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21872. return null;
  21873. }
  21874. var texture = BABYLON.SerializationHelper.Parse(function () {
  21875. if (parsedTexture.customType) {
  21876. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21877. return customTexture.Parse(parsedTexture, scene, rootUrl);
  21878. }
  21879. else if (parsedTexture.mirrorPlane) {
  21880. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21881. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21882. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21883. return mirrorTexture;
  21884. }
  21885. else if (parsedTexture.isRenderTarget) {
  21886. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21887. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21888. return renderTargetTexture;
  21889. }
  21890. else {
  21891. var texture;
  21892. if (parsedTexture.base64String) {
  21893. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21894. }
  21895. else {
  21896. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21897. }
  21898. return texture;
  21899. }
  21900. }, parsedTexture, scene);
  21901. // Animations
  21902. if (parsedTexture.animations) {
  21903. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21904. var parsedAnimation = parsedTexture.animations[animationIndex];
  21905. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21906. }
  21907. }
  21908. return texture;
  21909. };
  21910. // Constants
  21911. Texture.NEAREST_SAMPLINGMODE = 1;
  21912. Texture.BILINEAR_SAMPLINGMODE = 2;
  21913. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21914. Texture.EXPLICIT_MODE = 0;
  21915. Texture.SPHERICAL_MODE = 1;
  21916. Texture.PLANAR_MODE = 2;
  21917. Texture.CUBIC_MODE = 3;
  21918. Texture.PROJECTION_MODE = 4;
  21919. Texture.SKYBOX_MODE = 5;
  21920. Texture.INVCUBIC_MODE = 6;
  21921. Texture.EQUIRECTANGULAR_MODE = 7;
  21922. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21923. Texture.CLAMP_ADDRESSMODE = 0;
  21924. Texture.WRAP_ADDRESSMODE = 1;
  21925. Texture.MIRROR_ADDRESSMODE = 2;
  21926. __decorate([
  21927. BABYLON.serialize()
  21928. ], Texture.prototype, "url", void 0);
  21929. __decorate([
  21930. BABYLON.serialize()
  21931. ], Texture.prototype, "uOffset", void 0);
  21932. __decorate([
  21933. BABYLON.serialize()
  21934. ], Texture.prototype, "vOffset", void 0);
  21935. __decorate([
  21936. BABYLON.serialize()
  21937. ], Texture.prototype, "uScale", void 0);
  21938. __decorate([
  21939. BABYLON.serialize()
  21940. ], Texture.prototype, "vScale", void 0);
  21941. __decorate([
  21942. BABYLON.serialize()
  21943. ], Texture.prototype, "uAng", void 0);
  21944. __decorate([
  21945. BABYLON.serialize()
  21946. ], Texture.prototype, "vAng", void 0);
  21947. __decorate([
  21948. BABYLON.serialize()
  21949. ], Texture.prototype, "wAng", void 0);
  21950. return Texture;
  21951. })(BABYLON.BaseTexture);
  21952. BABYLON.Texture = Texture;
  21953. })(BABYLON || (BABYLON = {}));
  21954. var BABYLON;
  21955. (function (BABYLON) {
  21956. var CubeTexture = (function (_super) {
  21957. __extends(CubeTexture, _super);
  21958. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  21959. _super.call(this, scene);
  21960. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  21961. this.name = rootUrl;
  21962. this.url = rootUrl;
  21963. this._noMipmap = noMipmap;
  21964. this.hasAlpha = false;
  21965. if (!rootUrl && !files) {
  21966. return;
  21967. }
  21968. this._texture = this._getFromCache(rootUrl, noMipmap);
  21969. if (!files) {
  21970. if (!extensions) {
  21971. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  21972. }
  21973. files = [];
  21974. for (var index = 0; index < extensions.length; index++) {
  21975. files.push(rootUrl + extensions[index]);
  21976. }
  21977. this._extensions = extensions;
  21978. }
  21979. this._files = files;
  21980. if (!this._texture) {
  21981. if (!scene.useDelayedTextureLoading) {
  21982. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  21983. }
  21984. else {
  21985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21986. }
  21987. }
  21988. this.isCube = true;
  21989. this._textureMatrix = BABYLON.Matrix.Identity();
  21990. }
  21991. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  21992. return new CubeTexture("", scene, null, noMipmap, files);
  21993. };
  21994. // Methods
  21995. CubeTexture.prototype.delayLoad = function () {
  21996. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21997. return;
  21998. }
  21999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22000. this._texture = this._getFromCache(this.url, this._noMipmap);
  22001. if (!this._texture) {
  22002. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22003. }
  22004. };
  22005. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22006. return this._textureMatrix;
  22007. };
  22008. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22009. var texture = BABYLON.SerializationHelper.Parse(function () {
  22010. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22011. }, parsedTexture, scene);
  22012. // Animations
  22013. if (parsedTexture.animations) {
  22014. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22015. var parsedAnimation = parsedTexture.animations[animationIndex];
  22016. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22017. }
  22018. }
  22019. return texture;
  22020. };
  22021. CubeTexture.prototype.clone = function () {
  22022. var _this = this;
  22023. return BABYLON.SerializationHelper.Clone(function () {
  22024. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22025. }, this);
  22026. };
  22027. return CubeTexture;
  22028. })(BABYLON.BaseTexture);
  22029. BABYLON.CubeTexture = CubeTexture;
  22030. })(BABYLON || (BABYLON = {}));
  22031. var BABYLON;
  22032. (function (BABYLON) {
  22033. var RenderTargetTexture = (function (_super) {
  22034. __extends(RenderTargetTexture, _super);
  22035. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode) {
  22036. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22037. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22038. if (isCube === void 0) { isCube = false; }
  22039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22040. _super.call(this, null, scene, !generateMipMaps);
  22041. this.isCube = isCube;
  22042. /**
  22043. * Use this list to define the list of mesh you want to render.
  22044. */
  22045. this.renderList = new Array();
  22046. this.renderParticles = true;
  22047. this.renderSprites = false;
  22048. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22049. // Events
  22050. /**
  22051. * An event triggered when the texture is unbind.
  22052. * @type {BABYLON.Observable}
  22053. */
  22054. this.onAfterUnbindObservable = new BABYLON.Observable();
  22055. /**
  22056. * An event triggered before rendering the texture
  22057. * @type {BABYLON.Observable}
  22058. */
  22059. this.onBeforeRenderObservable = new BABYLON.Observable();
  22060. /**
  22061. * An event triggered after rendering the texture
  22062. * @type {BABYLON.Observable}
  22063. */
  22064. this.onAfterRenderObservable = new BABYLON.Observable();
  22065. /**
  22066. * An event triggered after the texture clear
  22067. * @type {BABYLON.Observable}
  22068. */
  22069. this.onClearObservable = new BABYLON.Observable();
  22070. this._currentRefreshId = -1;
  22071. this._refreshRate = 1;
  22072. this.name = name;
  22073. this.isRenderTarget = true;
  22074. this._size = size;
  22075. this._generateMipMaps = generateMipMaps;
  22076. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22077. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22078. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22079. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22080. }
  22081. if (isCube) {
  22082. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, samplingMode: samplingMode });
  22083. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22084. this._textureMatrix = BABYLON.Matrix.Identity();
  22085. }
  22086. else {
  22087. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type, samplingMode: samplingMode });
  22088. }
  22089. // Rendering groups
  22090. this._renderingManager = new BABYLON.RenderingManager(scene);
  22091. }
  22092. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22093. get: function () {
  22094. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22100. get: function () {
  22101. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22102. },
  22103. enumerable: true,
  22104. configurable: true
  22105. });
  22106. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22107. get: function () {
  22108. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22114. set: function (callback) {
  22115. if (this._onAfterUnbindObserver) {
  22116. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22117. }
  22118. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22119. },
  22120. enumerable: true,
  22121. configurable: true
  22122. });
  22123. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22124. set: function (callback) {
  22125. if (this._onBeforeRenderObserver) {
  22126. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22127. }
  22128. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22129. },
  22130. enumerable: true,
  22131. configurable: true
  22132. });
  22133. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22134. set: function (callback) {
  22135. if (this._onAfterRenderObserver) {
  22136. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22137. }
  22138. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22144. set: function (callback) {
  22145. if (this._onClearObserver) {
  22146. this.onClearObservable.remove(this._onClearObserver);
  22147. }
  22148. this._onClearObserver = this.onClearObservable.add(callback);
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22154. this._currentRefreshId = -1;
  22155. };
  22156. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22157. get: function () {
  22158. return this._refreshRate;
  22159. },
  22160. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22161. set: function (value) {
  22162. this._refreshRate = value;
  22163. this.resetRefreshCounter();
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. RenderTargetTexture.prototype._shouldRender = function () {
  22169. if (this._currentRefreshId === -1) {
  22170. this._currentRefreshId = 1;
  22171. return true;
  22172. }
  22173. if (this.refreshRate === this._currentRefreshId) {
  22174. this._currentRefreshId = 1;
  22175. return true;
  22176. }
  22177. this._currentRefreshId++;
  22178. return false;
  22179. };
  22180. RenderTargetTexture.prototype.isReady = function () {
  22181. if (!this.getScene().renderTargetsEnabled) {
  22182. return false;
  22183. }
  22184. return _super.prototype.isReady.call(this);
  22185. };
  22186. RenderTargetTexture.prototype.getRenderSize = function () {
  22187. return this._size;
  22188. };
  22189. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22190. get: function () {
  22191. return true;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. RenderTargetTexture.prototype.scale = function (ratio) {
  22197. var newSize = this._size * ratio;
  22198. this.resize(newSize, this._generateMipMaps);
  22199. };
  22200. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22201. if (this.isCube) {
  22202. return this._textureMatrix;
  22203. }
  22204. return _super.prototype.getReflectionTextureMatrix.call(this);
  22205. };
  22206. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22207. this.releaseInternalTexture();
  22208. if (this.isCube) {
  22209. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22210. }
  22211. else {
  22212. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22213. }
  22214. };
  22215. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22216. var scene = this.getScene();
  22217. if (this.useCameraPostProcesses !== undefined) {
  22218. useCameraPostProcess = this.useCameraPostProcesses;
  22219. }
  22220. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22221. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22222. }
  22223. if (this._waitingRenderList) {
  22224. this.renderList = [];
  22225. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22226. var id = this._waitingRenderList[index];
  22227. this.renderList.push(scene.getMeshByID(id));
  22228. }
  22229. delete this._waitingRenderList;
  22230. }
  22231. // Is predicate defined?
  22232. if (this.renderListPredicate) {
  22233. this.renderList.splice(0); // Clear previous renderList
  22234. var sceneMeshes = this.getScene().meshes;
  22235. for (var index = 0; index < sceneMeshes.length; index++) {
  22236. var mesh = sceneMeshes[index];
  22237. if (this.renderListPredicate(mesh)) {
  22238. this.renderList.push(mesh);
  22239. }
  22240. }
  22241. }
  22242. if (this.renderList && this.renderList.length === 0) {
  22243. return;
  22244. }
  22245. // Prepare renderingManager
  22246. this._renderingManager.reset();
  22247. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22248. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22249. var sceneRenderId = scene.getRenderId();
  22250. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22251. var mesh = currentRenderList[meshIndex];
  22252. if (mesh) {
  22253. if (!mesh.isReady()) {
  22254. // Reset _currentRefreshId
  22255. this.resetRefreshCounter();
  22256. continue;
  22257. }
  22258. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22259. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22260. mesh._activate(sceneRenderId);
  22261. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22262. var subMesh = mesh.subMeshes[subIndex];
  22263. scene._activeIndices.addCount(subMesh.indexCount, false);
  22264. this._renderingManager.dispatch(subMesh);
  22265. }
  22266. }
  22267. }
  22268. }
  22269. if (this.isCube) {
  22270. for (var face = 0; face < 6; face++) {
  22271. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22272. scene.incrementRenderId();
  22273. scene.resetCachedMaterial();
  22274. }
  22275. }
  22276. else {
  22277. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22278. }
  22279. this.onAfterUnbindObservable.notifyObservers(this);
  22280. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22281. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22282. }
  22283. scene.resetCachedMaterial();
  22284. };
  22285. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22286. var scene = this.getScene();
  22287. var engine = scene.getEngine();
  22288. // Bind
  22289. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22290. if (this.isCube) {
  22291. engine.bindFramebuffer(this._texture, faceIndex);
  22292. }
  22293. else {
  22294. engine.bindFramebuffer(this._texture);
  22295. }
  22296. }
  22297. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22298. // Clear
  22299. if (this.onClearObservable.hasObservers()) {
  22300. this.onClearObservable.notifyObservers(engine);
  22301. }
  22302. else {
  22303. engine.clear(scene.clearColor, true, true);
  22304. }
  22305. if (!this._doNotChangeAspectRatio) {
  22306. scene.updateTransformMatrix(true);
  22307. }
  22308. // Render
  22309. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22310. if (useCameraPostProcess) {
  22311. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22312. }
  22313. if (!this._doNotChangeAspectRatio) {
  22314. scene.updateTransformMatrix(true);
  22315. }
  22316. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22317. // Dump ?
  22318. if (dumpForDebug) {
  22319. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22320. }
  22321. // Unbind
  22322. if (!this.isCube || faceIndex === 5) {
  22323. if (this.isCube) {
  22324. if (faceIndex === 5) {
  22325. engine.generateMipMapsForCubemap(this._texture);
  22326. }
  22327. }
  22328. engine.unBindFramebuffer(this._texture, this.isCube);
  22329. }
  22330. };
  22331. RenderTargetTexture.prototype.clone = function () {
  22332. var textureSize = this.getSize();
  22333. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22334. // Base texture
  22335. newTexture.hasAlpha = this.hasAlpha;
  22336. newTexture.level = this.level;
  22337. // RenderTarget Texture
  22338. newTexture.coordinatesMode = this.coordinatesMode;
  22339. newTexture.renderList = this.renderList.slice(0);
  22340. return newTexture;
  22341. };
  22342. RenderTargetTexture.prototype.serialize = function () {
  22343. if (!this.name) {
  22344. return null;
  22345. }
  22346. var serializationObject = _super.prototype.serialize.call(this);
  22347. serializationObject.renderTargetSize = this.getRenderSize();
  22348. serializationObject.renderList = [];
  22349. for (var index = 0; index < this.renderList.length; index++) {
  22350. serializationObject.renderList.push(this.renderList[index].id);
  22351. }
  22352. return serializationObject;
  22353. };
  22354. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22355. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22356. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22357. return RenderTargetTexture;
  22358. })(BABYLON.Texture);
  22359. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22360. })(BABYLON || (BABYLON = {}));
  22361. var BABYLON;
  22362. (function (BABYLON) {
  22363. var ProceduralTexture = (function (_super) {
  22364. __extends(ProceduralTexture, _super);
  22365. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22366. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22367. if (isCube === void 0) { isCube = false; }
  22368. _super.call(this, null, scene, !generateMipMaps);
  22369. this.isCube = isCube;
  22370. this.isEnabled = true;
  22371. this._currentRefreshId = -1;
  22372. this._refreshRate = 1;
  22373. this._vertexBuffers = {};
  22374. this._uniforms = new Array();
  22375. this._samplers = new Array();
  22376. this._textures = new Array();
  22377. this._floats = new Array();
  22378. this._floatsArrays = {};
  22379. this._colors3 = new Array();
  22380. this._colors4 = new Array();
  22381. this._vectors2 = new Array();
  22382. this._vectors3 = new Array();
  22383. this._matrices = new Array();
  22384. this._fallbackTextureUsed = false;
  22385. scene._proceduralTextures.push(this);
  22386. this.name = name;
  22387. this.isRenderTarget = true;
  22388. this._size = size;
  22389. this._generateMipMaps = generateMipMaps;
  22390. this.setFragment(fragment);
  22391. this._fallbackTexture = fallbackTexture;
  22392. var engine = scene.getEngine();
  22393. if (isCube) {
  22394. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  22395. this.setFloat("face", 0);
  22396. }
  22397. else {
  22398. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  22399. }
  22400. // VBO
  22401. var vertices = [];
  22402. vertices.push(1, 1);
  22403. vertices.push(-1, 1);
  22404. vertices.push(-1, -1);
  22405. vertices.push(1, -1);
  22406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  22407. // Indices
  22408. var indices = [];
  22409. indices.push(0);
  22410. indices.push(1);
  22411. indices.push(2);
  22412. indices.push(0);
  22413. indices.push(2);
  22414. indices.push(3);
  22415. this._indexBuffer = engine.createIndexBuffer(indices);
  22416. }
  22417. ProceduralTexture.prototype.reset = function () {
  22418. if (this._effect === undefined) {
  22419. return;
  22420. }
  22421. var engine = this.getScene().getEngine();
  22422. engine._releaseEffect(this._effect);
  22423. };
  22424. ProceduralTexture.prototype.isReady = function () {
  22425. var _this = this;
  22426. var engine = this.getScene().getEngine();
  22427. var shaders;
  22428. if (!this._fragment) {
  22429. return false;
  22430. }
  22431. if (this._fallbackTextureUsed) {
  22432. return true;
  22433. }
  22434. if (this._fragment.fragmentElement !== undefined) {
  22435. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  22436. }
  22437. else {
  22438. shaders = { vertex: "procedural", fragment: this._fragment };
  22439. }
  22440. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  22441. _this.releaseInternalTexture();
  22442. if (_this._fallbackTexture) {
  22443. _this._texture = _this._fallbackTexture._texture;
  22444. _this._texture.references++;
  22445. }
  22446. _this._fallbackTextureUsed = true;
  22447. });
  22448. return this._effect.isReady();
  22449. };
  22450. ProceduralTexture.prototype.resetRefreshCounter = function () {
  22451. this._currentRefreshId = -1;
  22452. };
  22453. ProceduralTexture.prototype.setFragment = function (fragment) {
  22454. this._fragment = fragment;
  22455. };
  22456. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  22457. get: function () {
  22458. return this._refreshRate;
  22459. },
  22460. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22461. set: function (value) {
  22462. this._refreshRate = value;
  22463. this.resetRefreshCounter();
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. ProceduralTexture.prototype._shouldRender = function () {
  22469. if (!this.isEnabled || !this.isReady() || !this._texture) {
  22470. return false;
  22471. }
  22472. if (this._fallbackTextureUsed) {
  22473. return false;
  22474. }
  22475. if (this._currentRefreshId === -1) {
  22476. this._currentRefreshId = 1;
  22477. return true;
  22478. }
  22479. if (this.refreshRate === this._currentRefreshId) {
  22480. this._currentRefreshId = 1;
  22481. return true;
  22482. }
  22483. this._currentRefreshId++;
  22484. return false;
  22485. };
  22486. ProceduralTexture.prototype.getRenderSize = function () {
  22487. return this._size;
  22488. };
  22489. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  22490. if (this._fallbackTextureUsed) {
  22491. return;
  22492. }
  22493. this.releaseInternalTexture();
  22494. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22495. };
  22496. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  22497. if (this._uniforms.indexOf(uniformName) === -1) {
  22498. this._uniforms.push(uniformName);
  22499. }
  22500. };
  22501. ProceduralTexture.prototype.setTexture = function (name, texture) {
  22502. if (this._samplers.indexOf(name) === -1) {
  22503. this._samplers.push(name);
  22504. }
  22505. this._textures[name] = texture;
  22506. return this;
  22507. };
  22508. ProceduralTexture.prototype.setFloat = function (name, value) {
  22509. this._checkUniform(name);
  22510. this._floats[name] = value;
  22511. return this;
  22512. };
  22513. ProceduralTexture.prototype.setFloats = function (name, value) {
  22514. this._checkUniform(name);
  22515. this._floatsArrays[name] = value;
  22516. return this;
  22517. };
  22518. ProceduralTexture.prototype.setColor3 = function (name, value) {
  22519. this._checkUniform(name);
  22520. this._colors3[name] = value;
  22521. return this;
  22522. };
  22523. ProceduralTexture.prototype.setColor4 = function (name, value) {
  22524. this._checkUniform(name);
  22525. this._colors4[name] = value;
  22526. return this;
  22527. };
  22528. ProceduralTexture.prototype.setVector2 = function (name, value) {
  22529. this._checkUniform(name);
  22530. this._vectors2[name] = value;
  22531. return this;
  22532. };
  22533. ProceduralTexture.prototype.setVector3 = function (name, value) {
  22534. this._checkUniform(name);
  22535. this._vectors3[name] = value;
  22536. return this;
  22537. };
  22538. ProceduralTexture.prototype.setMatrix = function (name, value) {
  22539. this._checkUniform(name);
  22540. this._matrices[name] = value;
  22541. return this;
  22542. };
  22543. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22544. var scene = this.getScene();
  22545. var engine = scene.getEngine();
  22546. // Render
  22547. engine.enableEffect(this._effect);
  22548. engine.setState(false);
  22549. // Texture
  22550. for (var name in this._textures) {
  22551. this._effect.setTexture(name, this._textures[name]);
  22552. }
  22553. // Float
  22554. for (name in this._floats) {
  22555. this._effect.setFloat(name, this._floats[name]);
  22556. }
  22557. // Floats
  22558. for (name in this._floatsArrays) {
  22559. this._effect.setArray(name, this._floatsArrays[name]);
  22560. }
  22561. // Color3
  22562. for (name in this._colors3) {
  22563. this._effect.setColor3(name, this._colors3[name]);
  22564. }
  22565. // Color4
  22566. for (name in this._colors4) {
  22567. var color = this._colors4[name];
  22568. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22569. }
  22570. // Vector2
  22571. for (name in this._vectors2) {
  22572. this._effect.setVector2(name, this._vectors2[name]);
  22573. }
  22574. // Vector3
  22575. for (name in this._vectors3) {
  22576. this._effect.setVector3(name, this._vectors3[name]);
  22577. }
  22578. // Matrix
  22579. for (name in this._matrices) {
  22580. this._effect.setMatrix(name, this._matrices[name]);
  22581. }
  22582. // VBOs
  22583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  22584. if (this.isCube) {
  22585. for (var face = 0; face < 6; face++) {
  22586. engine.bindFramebuffer(this._texture, face);
  22587. this._effect.setFloat("face", face);
  22588. // Clear
  22589. engine.clear(scene.clearColor, true, true);
  22590. // Draw order
  22591. engine.draw(true, 0, 6);
  22592. // Mipmaps
  22593. if (face === 5) {
  22594. engine.generateMipMapsForCubemap(this._texture);
  22595. }
  22596. }
  22597. }
  22598. else {
  22599. engine.bindFramebuffer(this._texture);
  22600. // Clear
  22601. engine.clear(scene.clearColor, true, true);
  22602. // Draw order
  22603. engine.draw(true, 0, 6);
  22604. }
  22605. // Unbind
  22606. engine.unBindFramebuffer(this._texture, this.isCube);
  22607. if (this.onGenerated) {
  22608. this.onGenerated();
  22609. }
  22610. };
  22611. ProceduralTexture.prototype.clone = function () {
  22612. var textureSize = this.getSize();
  22613. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  22614. // Base texture
  22615. newTexture.hasAlpha = this.hasAlpha;
  22616. newTexture.level = this.level;
  22617. // RenderTarget Texture
  22618. newTexture.coordinatesMode = this.coordinatesMode;
  22619. return newTexture;
  22620. };
  22621. ProceduralTexture.prototype.dispose = function () {
  22622. var index = this.getScene()._proceduralTextures.indexOf(this);
  22623. if (index >= 0) {
  22624. this.getScene()._proceduralTextures.splice(index, 1);
  22625. }
  22626. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  22627. if (vertexBuffer) {
  22628. vertexBuffer.dispose();
  22629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  22630. }
  22631. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  22632. this._indexBuffer = null;
  22633. }
  22634. _super.prototype.dispose.call(this);
  22635. };
  22636. return ProceduralTexture;
  22637. })(BABYLON.Texture);
  22638. BABYLON.ProceduralTexture = ProceduralTexture;
  22639. })(BABYLON || (BABYLON = {}));
  22640. var BABYLON;
  22641. (function (BABYLON) {
  22642. var MirrorTexture = (function (_super) {
  22643. __extends(MirrorTexture, _super);
  22644. function MirrorTexture(name, size, scene, generateMipMaps) {
  22645. var _this = this;
  22646. _super.call(this, name, size, scene, generateMipMaps, true);
  22647. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  22648. this._transformMatrix = BABYLON.Matrix.Zero();
  22649. this._mirrorMatrix = BABYLON.Matrix.Zero();
  22650. this.onBeforeRenderObservable.add(function () {
  22651. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  22652. _this._savedViewMatrix = scene.getViewMatrix();
  22653. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  22654. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  22655. scene.clipPlane = _this.mirrorPlane;
  22656. scene.getEngine().cullBackFaces = false;
  22657. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  22658. });
  22659. this.onAfterRenderObservable.add(function () {
  22660. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  22661. scene.getEngine().cullBackFaces = true;
  22662. scene._mirroredCameraPosition = null;
  22663. delete scene.clipPlane;
  22664. });
  22665. }
  22666. MirrorTexture.prototype.clone = function () {
  22667. var textureSize = this.getSize();
  22668. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22669. // Base texture
  22670. newTexture.hasAlpha = this.hasAlpha;
  22671. newTexture.level = this.level;
  22672. // Mirror Texture
  22673. newTexture.mirrorPlane = this.mirrorPlane.clone();
  22674. newTexture.renderList = this.renderList.slice(0);
  22675. return newTexture;
  22676. };
  22677. MirrorTexture.prototype.serialize = function () {
  22678. if (!this.name) {
  22679. return null;
  22680. }
  22681. var serializationObject = _super.prototype.serialize.call(this);
  22682. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  22683. return serializationObject;
  22684. };
  22685. return MirrorTexture;
  22686. })(BABYLON.RenderTargetTexture);
  22687. BABYLON.MirrorTexture = MirrorTexture;
  22688. })(BABYLON || (BABYLON = {}));
  22689. var BABYLON;
  22690. (function (BABYLON) {
  22691. /**
  22692. * Creates a refraction texture used by refraction channel of the standard material.
  22693. * @param name the texture name
  22694. * @param size size of the underlying texture
  22695. * @param scene root scene
  22696. */
  22697. var RefractionTexture = (function (_super) {
  22698. __extends(RefractionTexture, _super);
  22699. function RefractionTexture(name, size, scene, generateMipMaps) {
  22700. var _this = this;
  22701. _super.call(this, name, size, scene, generateMipMaps, true);
  22702. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  22703. this.depth = 2.0;
  22704. this.onBeforeRenderObservable.add(function () {
  22705. scene.clipPlane = _this.refractionPlane;
  22706. });
  22707. this.onAfterRenderObservable.add(function () {
  22708. delete scene.clipPlane;
  22709. });
  22710. }
  22711. RefractionTexture.prototype.clone = function () {
  22712. var textureSize = this.getSize();
  22713. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22714. // Base texture
  22715. newTexture.hasAlpha = this.hasAlpha;
  22716. newTexture.level = this.level;
  22717. // Refraction Texture
  22718. newTexture.refractionPlane = this.refractionPlane.clone();
  22719. newTexture.renderList = this.renderList.slice(0);
  22720. newTexture.depth = this.depth;
  22721. return newTexture;
  22722. };
  22723. RefractionTexture.prototype.serialize = function () {
  22724. if (!this.name) {
  22725. return null;
  22726. }
  22727. var serializationObject = _super.prototype.serialize.call(this);
  22728. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  22729. serializationObject.depth = this.depth;
  22730. return serializationObject;
  22731. };
  22732. return RefractionTexture;
  22733. })(BABYLON.RenderTargetTexture);
  22734. BABYLON.RefractionTexture = RefractionTexture;
  22735. })(BABYLON || (BABYLON = {}));
  22736. var BABYLON;
  22737. (function (BABYLON) {
  22738. var DynamicTexture = (function (_super) {
  22739. __extends(DynamicTexture, _super);
  22740. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  22741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22742. _super.call(this, null, scene, !generateMipMaps);
  22743. this.name = name;
  22744. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22745. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22746. this._generateMipMaps = generateMipMaps;
  22747. if (options.getContext) {
  22748. this._canvas = options;
  22749. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22750. }
  22751. else {
  22752. this._canvas = document.createElement("canvas");
  22753. if (options.width) {
  22754. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  22755. }
  22756. else {
  22757. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  22758. }
  22759. }
  22760. var textureSize = this.getSize();
  22761. this._canvas.width = textureSize.width;
  22762. this._canvas.height = textureSize.height;
  22763. this._context = this._canvas.getContext("2d");
  22764. }
  22765. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  22766. get: function () {
  22767. return true;
  22768. },
  22769. enumerable: true,
  22770. configurable: true
  22771. });
  22772. DynamicTexture.prototype.scale = function (ratio) {
  22773. var textureSize = this.getSize();
  22774. textureSize.width *= ratio;
  22775. textureSize.height *= ratio;
  22776. this._canvas.width = textureSize.width;
  22777. this._canvas.height = textureSize.height;
  22778. this.releaseInternalTexture();
  22779. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  22780. };
  22781. DynamicTexture.prototype.getContext = function () {
  22782. return this._context;
  22783. };
  22784. DynamicTexture.prototype.clear = function () {
  22785. var size = this.getSize();
  22786. this._context.fillRect(0, 0, size.width, size.height);
  22787. };
  22788. DynamicTexture.prototype.update = function (invertY) {
  22789. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  22790. };
  22791. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  22792. if (update === void 0) { update = true; }
  22793. var size = this.getSize();
  22794. if (clearColor) {
  22795. this._context.fillStyle = clearColor;
  22796. this._context.fillRect(0, 0, size.width, size.height);
  22797. }
  22798. this._context.font = font;
  22799. if (x === null) {
  22800. var textSize = this._context.measureText(text);
  22801. x = (size.width - textSize.width) / 2;
  22802. }
  22803. this._context.fillStyle = color;
  22804. this._context.fillText(text, x, y);
  22805. if (update) {
  22806. this.update(invertY);
  22807. }
  22808. };
  22809. DynamicTexture.prototype.clone = function () {
  22810. var textureSize = this.getSize();
  22811. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  22812. // Base texture
  22813. newTexture.hasAlpha = this.hasAlpha;
  22814. newTexture.level = this.level;
  22815. // Dynamic Texture
  22816. newTexture.wrapU = this.wrapU;
  22817. newTexture.wrapV = this.wrapV;
  22818. return newTexture;
  22819. };
  22820. return DynamicTexture;
  22821. })(BABYLON.Texture);
  22822. BABYLON.DynamicTexture = DynamicTexture;
  22823. })(BABYLON || (BABYLON = {}));
  22824. var BABYLON;
  22825. (function (BABYLON) {
  22826. var VideoTexture = (function (_super) {
  22827. __extends(VideoTexture, _super);
  22828. /**
  22829. * Creates a video texture.
  22830. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  22831. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  22832. * @param {BABYLON.Scene} scene is obviously the current scene.
  22833. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  22834. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  22835. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  22836. */
  22837. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  22838. var _this = this;
  22839. if (generateMipMaps === void 0) { generateMipMaps = false; }
  22840. if (invertY === void 0) { invertY = false; }
  22841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22842. _super.call(this, null, scene, !generateMipMaps, invertY);
  22843. this._autoLaunch = true;
  22844. var urls;
  22845. this.name = name;
  22846. if (urlsOrVideo instanceof HTMLVideoElement) {
  22847. this.video = urlsOrVideo;
  22848. }
  22849. else {
  22850. urls = urlsOrVideo;
  22851. this.video = document.createElement("video");
  22852. this.video.autoplay = false;
  22853. this.video.loop = true;
  22854. }
  22855. this._generateMipMaps = generateMipMaps;
  22856. this._samplingMode = samplingMode;
  22857. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  22858. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22859. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22860. }
  22861. else {
  22862. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22863. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22864. this._generateMipMaps = false;
  22865. }
  22866. if (urls) {
  22867. this.video.addEventListener("canplaythrough", function () {
  22868. _this._createTexture();
  22869. });
  22870. urls.forEach(function (url) {
  22871. var source = document.createElement("source");
  22872. source.src = url;
  22873. _this.video.appendChild(source);
  22874. });
  22875. }
  22876. else {
  22877. this._createTexture();
  22878. }
  22879. this._lastUpdate = BABYLON.Tools.Now;
  22880. }
  22881. VideoTexture.prototype._createTexture = function () {
  22882. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  22883. this._texture.isReady = true;
  22884. };
  22885. VideoTexture.prototype.update = function () {
  22886. if (this._autoLaunch) {
  22887. this._autoLaunch = false;
  22888. this.video.play();
  22889. }
  22890. var now = BABYLON.Tools.Now;
  22891. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  22892. return false;
  22893. }
  22894. this._lastUpdate = now;
  22895. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  22896. return true;
  22897. };
  22898. return VideoTexture;
  22899. })(BABYLON.Texture);
  22900. BABYLON.VideoTexture = VideoTexture;
  22901. })(BABYLON || (BABYLON = {}));
  22902. var BABYLON;
  22903. (function (BABYLON) {
  22904. var CustomProceduralTexture = (function (_super) {
  22905. __extends(CustomProceduralTexture, _super);
  22906. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  22907. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  22908. this._animate = true;
  22909. this._time = 0;
  22910. this._texturePath = texturePath;
  22911. //Try to load json
  22912. this.loadJson(texturePath);
  22913. this.refreshRate = 1;
  22914. }
  22915. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  22916. var _this = this;
  22917. var that = this;
  22918. function noConfigFile() {
  22919. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  22920. try {
  22921. that.setFragment(that._texturePath);
  22922. }
  22923. catch (ex) {
  22924. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  22925. }
  22926. }
  22927. var configFileUrl = jsonUrl + "/config.json";
  22928. var xhr = new XMLHttpRequest();
  22929. xhr.open("GET", configFileUrl, true);
  22930. xhr.addEventListener("load", function () {
  22931. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  22932. try {
  22933. _this._config = JSON.parse(xhr.response);
  22934. _this.updateShaderUniforms();
  22935. _this.updateTextures();
  22936. _this.setFragment(_this._texturePath + "/custom");
  22937. _this._animate = _this._config.animate;
  22938. _this.refreshRate = _this._config.refreshrate;
  22939. }
  22940. catch (ex) {
  22941. noConfigFile();
  22942. }
  22943. }
  22944. else {
  22945. noConfigFile();
  22946. }
  22947. }, false);
  22948. xhr.addEventListener("error", function () {
  22949. noConfigFile();
  22950. }, false);
  22951. try {
  22952. xhr.send();
  22953. }
  22954. catch (ex) {
  22955. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  22956. }
  22957. };
  22958. CustomProceduralTexture.prototype.isReady = function () {
  22959. if (!_super.prototype.isReady.call(this)) {
  22960. return false;
  22961. }
  22962. for (var name in this._textures) {
  22963. var texture = this._textures[name];
  22964. if (!texture.isReady()) {
  22965. return false;
  22966. }
  22967. }
  22968. return true;
  22969. };
  22970. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  22971. if (this._animate) {
  22972. this._time += this.getScene().getAnimationRatio() * 0.03;
  22973. this.updateShaderUniforms();
  22974. }
  22975. _super.prototype.render.call(this, useCameraPostProcess);
  22976. };
  22977. CustomProceduralTexture.prototype.updateTextures = function () {
  22978. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  22979. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  22980. }
  22981. };
  22982. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  22983. if (this._config) {
  22984. for (var j = 0; j < this._config.uniforms.length; j++) {
  22985. var uniform = this._config.uniforms[j];
  22986. switch (uniform.type) {
  22987. case "float":
  22988. this.setFloat(uniform.name, uniform.value);
  22989. break;
  22990. case "color3":
  22991. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  22992. break;
  22993. case "color4":
  22994. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  22995. break;
  22996. case "vector2":
  22997. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  22998. break;
  22999. case "vector3":
  23000. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23001. break;
  23002. }
  23003. }
  23004. }
  23005. this.setFloat("time", this._time);
  23006. };
  23007. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23008. get: function () {
  23009. return this._animate;
  23010. },
  23011. set: function (value) {
  23012. this._animate = value;
  23013. },
  23014. enumerable: true,
  23015. configurable: true
  23016. });
  23017. return CustomProceduralTexture;
  23018. })(BABYLON.ProceduralTexture);
  23019. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23020. })(BABYLON || (BABYLON = {}));
  23021. var BABYLON;
  23022. (function (BABYLON) {
  23023. var EffectFallbacks = (function () {
  23024. function EffectFallbacks() {
  23025. this._defines = {};
  23026. this._currentRank = 32;
  23027. this._maxRank = -1;
  23028. }
  23029. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23030. if (!this._defines[rank]) {
  23031. if (rank < this._currentRank) {
  23032. this._currentRank = rank;
  23033. }
  23034. if (rank > this._maxRank) {
  23035. this._maxRank = rank;
  23036. }
  23037. this._defines[rank] = new Array();
  23038. }
  23039. this._defines[rank].push(define);
  23040. };
  23041. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23042. this._meshRank = rank;
  23043. this._mesh = mesh;
  23044. if (rank > this._maxRank) {
  23045. this._maxRank = rank;
  23046. }
  23047. };
  23048. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23049. get: function () {
  23050. return this._currentRank <= this._maxRank;
  23051. },
  23052. enumerable: true,
  23053. configurable: true
  23054. });
  23055. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23056. var currentFallbacks = this._defines[this._currentRank];
  23057. for (var index = 0; index < currentFallbacks.length; index++) {
  23058. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23059. }
  23060. if (this._mesh && this._currentRank === this._meshRank) {
  23061. this._mesh.computeBonesUsingShaders = false;
  23062. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23063. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23064. }
  23065. this._currentRank++;
  23066. return currentDefines;
  23067. };
  23068. return EffectFallbacks;
  23069. })();
  23070. BABYLON.EffectFallbacks = EffectFallbacks;
  23071. var Effect = (function () {
  23072. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23073. var _this = this;
  23074. this._isReady = false;
  23075. this._compilationError = "";
  23076. this._valueCache = {};
  23077. this._engine = engine;
  23078. this.name = baseName;
  23079. this.defines = defines;
  23080. this._uniformsNames = uniformsNames.concat(samplers);
  23081. this._samplers = samplers;
  23082. this._attributesNames = attributesNames;
  23083. this.onError = onError;
  23084. this.onCompiled = onCompiled;
  23085. this._indexParameters = indexParameters;
  23086. var vertexSource;
  23087. var fragmentSource;
  23088. if (baseName.vertexElement) {
  23089. vertexSource = document.getElementById(baseName.vertexElement);
  23090. if (!vertexSource) {
  23091. vertexSource = baseName.vertexElement;
  23092. }
  23093. }
  23094. else {
  23095. vertexSource = baseName.vertex || baseName;
  23096. }
  23097. if (baseName.fragmentElement) {
  23098. fragmentSource = document.getElementById(baseName.fragmentElement);
  23099. if (!fragmentSource) {
  23100. fragmentSource = baseName.fragmentElement;
  23101. }
  23102. }
  23103. else {
  23104. fragmentSource = baseName.fragment || baseName;
  23105. }
  23106. this._loadVertexShader(vertexSource, function (vertexCode) {
  23107. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23108. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23109. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23110. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23111. });
  23112. });
  23113. });
  23114. });
  23115. }
  23116. // Properties
  23117. Effect.prototype.isReady = function () {
  23118. return this._isReady;
  23119. };
  23120. Effect.prototype.getProgram = function () {
  23121. return this._program;
  23122. };
  23123. Effect.prototype.getAttributesNames = function () {
  23124. return this._attributesNames;
  23125. };
  23126. Effect.prototype.getAttributeLocation = function (index) {
  23127. return this._attributes[index];
  23128. };
  23129. Effect.prototype.getAttributeLocationByName = function (name) {
  23130. var index = this._attributesNames.indexOf(name);
  23131. return this._attributes[index];
  23132. };
  23133. Effect.prototype.getAttributesCount = function () {
  23134. return this._attributes.length;
  23135. };
  23136. Effect.prototype.getUniformIndex = function (uniformName) {
  23137. return this._uniformsNames.indexOf(uniformName);
  23138. };
  23139. Effect.prototype.getUniform = function (uniformName) {
  23140. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23141. };
  23142. Effect.prototype.getSamplers = function () {
  23143. return this._samplers;
  23144. };
  23145. Effect.prototype.getCompilationError = function () {
  23146. return this._compilationError;
  23147. };
  23148. // Methods
  23149. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23150. // DOM element ?
  23151. if (vertex instanceof HTMLElement) {
  23152. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23153. callback(vertexCode);
  23154. return;
  23155. }
  23156. // Is in local store ?
  23157. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23158. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23159. return;
  23160. }
  23161. var vertexShaderUrl;
  23162. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23163. vertexShaderUrl = vertex;
  23164. }
  23165. else {
  23166. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23167. }
  23168. // Vertex shader
  23169. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23170. };
  23171. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23172. // DOM element ?
  23173. if (fragment instanceof HTMLElement) {
  23174. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23175. callback(fragmentCode);
  23176. return;
  23177. }
  23178. // Is in local store ?
  23179. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23180. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23181. return;
  23182. }
  23183. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23184. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23185. return;
  23186. }
  23187. var fragmentShaderUrl;
  23188. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23189. fragmentShaderUrl = fragment;
  23190. }
  23191. else {
  23192. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23193. }
  23194. // Fragment shader
  23195. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23196. };
  23197. Effect.prototype._dumpShadersName = function () {
  23198. if (this.name.vertexElement) {
  23199. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23200. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23201. }
  23202. else if (this.name.vertex) {
  23203. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23204. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23205. }
  23206. else {
  23207. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23208. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23209. }
  23210. };
  23211. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23212. var _this = this;
  23213. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23214. var match = regex.exec(sourceCode);
  23215. var returnValue = new String(sourceCode);
  23216. while (match != null) {
  23217. var includeFile = match[1];
  23218. if (Effect.IncludesShadersStore[includeFile]) {
  23219. // Substitution
  23220. var includeContent = Effect.IncludesShadersStore[includeFile];
  23221. if (match[2]) {
  23222. var splits = match[3].split(",");
  23223. for (var index = 0; index < splits.length; index += 2) {
  23224. var source = new RegExp(splits[index], "g");
  23225. var dest = splits[index + 1];
  23226. includeContent = includeContent.replace(source, dest);
  23227. }
  23228. }
  23229. if (match[4]) {
  23230. var indexString = match[5];
  23231. if (indexString.indexOf("..") !== -1) {
  23232. var indexSplits = indexString.split("..");
  23233. var minIndex = parseInt(indexSplits[0]);
  23234. var maxIndex = parseInt(indexSplits[1]);
  23235. var sourceIncludeContent = includeContent.slice(0);
  23236. includeContent = "";
  23237. if (isNaN(maxIndex)) {
  23238. maxIndex = this._indexParameters[indexSplits[1]];
  23239. }
  23240. for (var i = minIndex; i <= maxIndex; i++) {
  23241. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23242. }
  23243. }
  23244. else {
  23245. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23246. }
  23247. }
  23248. // Replace
  23249. returnValue = returnValue.replace(match[0], includeContent);
  23250. }
  23251. else {
  23252. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23253. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23254. Effect.IncludesShadersStore[includeFile] = fileContent;
  23255. _this._processIncludes(returnValue, callback);
  23256. });
  23257. return;
  23258. }
  23259. match = regex.exec(sourceCode);
  23260. }
  23261. callback(returnValue);
  23262. };
  23263. Effect.prototype._processPrecision = function (source) {
  23264. if (source.indexOf("precision highp float") === -1) {
  23265. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23266. source = "precision mediump float;\n" + source;
  23267. }
  23268. else {
  23269. source = "precision highp float;\n" + source;
  23270. }
  23271. }
  23272. else {
  23273. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23274. source = source.replace("precision highp float", "precision mediump float");
  23275. }
  23276. }
  23277. return source;
  23278. };
  23279. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23280. try {
  23281. var engine = this._engine;
  23282. // Precision
  23283. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23284. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23285. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23286. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23287. this._attributes = engine.getAttributes(this._program, attributesNames);
  23288. var index;
  23289. for (index = 0; index < this._samplers.length; index++) {
  23290. var sampler = this.getUniform(this._samplers[index]);
  23291. if (sampler == null) {
  23292. this._samplers.splice(index, 1);
  23293. index--;
  23294. }
  23295. }
  23296. engine.bindSamplers(this);
  23297. this._isReady = true;
  23298. if (this.onCompiled) {
  23299. this.onCompiled(this);
  23300. }
  23301. }
  23302. catch (e) {
  23303. // Let's go through fallbacks then
  23304. if (fallbacks && fallbacks.isMoreFallbacks) {
  23305. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23306. this._dumpShadersName();
  23307. defines = fallbacks.reduce(defines);
  23308. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23309. }
  23310. else {
  23311. BABYLON.Tools.Error("Unable to compile effect: ");
  23312. this._dumpShadersName();
  23313. BABYLON.Tools.Error("Defines: " + defines);
  23314. BABYLON.Tools.Error("Error: " + e.message);
  23315. this._compilationError = e.message;
  23316. if (this.onError) {
  23317. this.onError(this, this._compilationError);
  23318. }
  23319. }
  23320. }
  23321. };
  23322. Object.defineProperty(Effect.prototype, "isSupported", {
  23323. get: function () {
  23324. return this._compilationError === "";
  23325. },
  23326. enumerable: true,
  23327. configurable: true
  23328. });
  23329. Effect.prototype._bindTexture = function (channel, texture) {
  23330. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23331. };
  23332. Effect.prototype.setTexture = function (channel, texture) {
  23333. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23334. };
  23335. Effect.prototype.setTextureArray = function (channel, textures) {
  23336. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23337. var initialPos = this._samplers.indexOf(channel);
  23338. for (var index = 1; index < textures.length; index++) {
  23339. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23340. }
  23341. }
  23342. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23343. };
  23344. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23345. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23346. };
  23347. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23348. var changed = false;
  23349. var cache = this._valueCache[uniformName];
  23350. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23351. changed = true;
  23352. cache = new BABYLON.Matrix();
  23353. }
  23354. var tm = cache.m;
  23355. var om = matrix.m;
  23356. for (var index = 0; index < 16; index++) {
  23357. if (tm[index] !== om[index]) {
  23358. tm[index] = om[index];
  23359. changed = true;
  23360. }
  23361. }
  23362. this._valueCache[uniformName] = cache;
  23363. return changed;
  23364. };
  23365. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23366. var cache = this._valueCache[uniformName];
  23367. if (!cache) {
  23368. cache = [x, y];
  23369. this._valueCache[uniformName] = cache;
  23370. return true;
  23371. }
  23372. var changed = false;
  23373. if (cache[0] !== x) {
  23374. cache[0] = x;
  23375. changed = true;
  23376. }
  23377. if (cache[1] !== y) {
  23378. cache[1] = y;
  23379. changed = true;
  23380. }
  23381. return changed;
  23382. };
  23383. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23384. var cache = this._valueCache[uniformName];
  23385. if (!cache) {
  23386. cache = [x, y, z];
  23387. this._valueCache[uniformName] = cache;
  23388. return true;
  23389. }
  23390. var changed = false;
  23391. if (cache[0] !== x) {
  23392. cache[0] = x;
  23393. changed = true;
  23394. }
  23395. if (cache[1] !== y) {
  23396. cache[1] = y;
  23397. changed = true;
  23398. }
  23399. if (cache[2] !== z) {
  23400. cache[2] = z;
  23401. changed = true;
  23402. }
  23403. return changed;
  23404. };
  23405. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23406. var cache = this._valueCache[uniformName];
  23407. if (!cache) {
  23408. cache = [x, y, z, w];
  23409. this._valueCache[uniformName] = cache;
  23410. return true;
  23411. }
  23412. var changed = false;
  23413. if (cache[0] !== x) {
  23414. cache[0] = x;
  23415. changed = true;
  23416. }
  23417. if (cache[1] !== y) {
  23418. cache[1] = y;
  23419. changed = true;
  23420. }
  23421. if (cache[2] !== z) {
  23422. cache[2] = z;
  23423. changed = true;
  23424. }
  23425. if (cache[3] !== w) {
  23426. cache[3] = w;
  23427. changed = true;
  23428. }
  23429. return changed;
  23430. };
  23431. Effect.prototype.setIntArray = function (uniformName, array) {
  23432. this._valueCache[uniformName] = null;
  23433. this._engine.setIntArray(this.getUniform(uniformName), array);
  23434. return this;
  23435. };
  23436. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23437. this._valueCache[uniformName] = null;
  23438. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23439. return this;
  23440. };
  23441. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23442. this._valueCache[uniformName] = null;
  23443. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23444. return this;
  23445. };
  23446. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23447. this._valueCache[uniformName] = null;
  23448. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23449. return this;
  23450. };
  23451. Effect.prototype.setFloatArray = function (uniformName, array) {
  23452. this._valueCache[uniformName] = null;
  23453. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23454. return this;
  23455. };
  23456. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23457. this._valueCache[uniformName] = null;
  23458. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23459. return this;
  23460. };
  23461. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23462. this._valueCache[uniformName] = null;
  23463. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23464. return this;
  23465. };
  23466. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23467. this._valueCache[uniformName] = null;
  23468. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23469. return this;
  23470. };
  23471. Effect.prototype.setArray = function (uniformName, array) {
  23472. this._valueCache[uniformName] = null;
  23473. this._engine.setArray(this.getUniform(uniformName), array);
  23474. return this;
  23475. };
  23476. Effect.prototype.setArray2 = function (uniformName, array) {
  23477. this._valueCache[uniformName] = null;
  23478. this._engine.setArray2(this.getUniform(uniformName), array);
  23479. return this;
  23480. };
  23481. Effect.prototype.setArray3 = function (uniformName, array) {
  23482. this._valueCache[uniformName] = null;
  23483. this._engine.setArray3(this.getUniform(uniformName), array);
  23484. return this;
  23485. };
  23486. Effect.prototype.setArray4 = function (uniformName, array) {
  23487. this._valueCache[uniformName] = null;
  23488. this._engine.setArray4(this.getUniform(uniformName), array);
  23489. return this;
  23490. };
  23491. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23492. this._valueCache[uniformName] = null;
  23493. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23494. return this;
  23495. };
  23496. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23497. if (this._cacheMatrix(uniformName, matrix)) {
  23498. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23499. }
  23500. return this;
  23501. };
  23502. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23503. this._valueCache[uniformName] = null;
  23504. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23505. return this;
  23506. };
  23507. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23508. this._valueCache[uniformName] = null;
  23509. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23510. return this;
  23511. };
  23512. Effect.prototype.setFloat = function (uniformName, value) {
  23513. var cache = this._valueCache[uniformName];
  23514. if (cache !== undefined && cache === value)
  23515. return this;
  23516. this._valueCache[uniformName] = value;
  23517. this._engine.setFloat(this.getUniform(uniformName), value);
  23518. return this;
  23519. };
  23520. Effect.prototype.setBool = function (uniformName, bool) {
  23521. var cache = this._valueCache[uniformName];
  23522. if (cache !== undefined && cache === bool)
  23523. return this;
  23524. this._valueCache[uniformName] = bool;
  23525. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23526. return this;
  23527. };
  23528. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23529. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23530. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23531. }
  23532. return this;
  23533. };
  23534. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23535. if (this._cacheFloat2(uniformName, x, y)) {
  23536. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23537. }
  23538. return this;
  23539. };
  23540. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23541. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23542. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23543. }
  23544. return this;
  23545. };
  23546. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23547. if (this._cacheFloat3(uniformName, x, y, z)) {
  23548. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23549. }
  23550. return this;
  23551. };
  23552. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23553. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23554. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23555. }
  23556. return this;
  23557. };
  23558. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23559. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23560. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23561. }
  23562. return this;
  23563. };
  23564. Effect.prototype.setColor3 = function (uniformName, color3) {
  23565. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23566. this._engine.setColor3(this.getUniform(uniformName), color3);
  23567. }
  23568. return this;
  23569. };
  23570. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23571. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23572. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23573. }
  23574. return this;
  23575. };
  23576. // Statics
  23577. Effect.ShadersStore = {};
  23578. Effect.IncludesShadersStore = {};
  23579. return Effect;
  23580. })();
  23581. BABYLON.Effect = Effect;
  23582. })(BABYLON || (BABYLON = {}));
  23583. var BABYLON;
  23584. (function (BABYLON) {
  23585. var MaterialHelper = (function () {
  23586. function MaterialHelper() {
  23587. }
  23588. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  23589. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23590. var lightIndex = 0;
  23591. var needNormals = false;
  23592. var needRebuild = false;
  23593. var needShadows = false;
  23594. for (var index = 0; index < scene.lights.length; index++) {
  23595. var light = scene.lights[index];
  23596. if (!light.isEnabled()) {
  23597. continue;
  23598. }
  23599. // Excluded check
  23600. if (light._excludedMeshesIds.length > 0) {
  23601. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  23602. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  23603. if (excludedMesh) {
  23604. light.excludedMeshes.push(excludedMesh);
  23605. }
  23606. }
  23607. light._excludedMeshesIds = [];
  23608. }
  23609. // Included check
  23610. if (light._includedOnlyMeshesIds.length > 0) {
  23611. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  23612. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  23613. if (includedOnlyMesh) {
  23614. light.includedOnlyMeshes.push(includedOnlyMesh);
  23615. }
  23616. }
  23617. light._includedOnlyMeshesIds = [];
  23618. }
  23619. if (!light.canAffectMesh(mesh)) {
  23620. continue;
  23621. }
  23622. needNormals = true;
  23623. if (defines["LIGHT" + lightIndex] === undefined) {
  23624. needRebuild = true;
  23625. }
  23626. defines["LIGHT" + lightIndex] = true;
  23627. var type;
  23628. if (light instanceof BABYLON.SpotLight) {
  23629. type = "SPOTLIGHT" + lightIndex;
  23630. }
  23631. else if (light instanceof BABYLON.HemisphericLight) {
  23632. type = "HEMILIGHT" + lightIndex;
  23633. }
  23634. else if (light instanceof BABYLON.PointLight) {
  23635. type = "POINTLIGHT" + lightIndex;
  23636. }
  23637. else {
  23638. type = "DIRLIGHT" + lightIndex;
  23639. }
  23640. if (defines[type] === undefined) {
  23641. needRebuild = true;
  23642. }
  23643. defines[type] = true;
  23644. // Specular
  23645. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  23646. defines["SPECULARTERM"] = true;
  23647. }
  23648. // Shadows
  23649. if (scene.shadowsEnabled) {
  23650. var shadowGenerator = light.getShadowGenerator();
  23651. if (mesh && mesh.receiveShadows && shadowGenerator) {
  23652. if (defines["SHADOW" + lightIndex] === undefined) {
  23653. needRebuild = true;
  23654. }
  23655. defines["SHADOW" + lightIndex] = true;
  23656. defines["SHADOWS"] = true;
  23657. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  23658. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  23659. needRebuild = true;
  23660. }
  23661. defines["SHADOWVSM" + lightIndex] = true;
  23662. }
  23663. if (shadowGenerator.usePoissonSampling) {
  23664. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  23665. needRebuild = true;
  23666. }
  23667. defines["SHADOWPCF" + lightIndex] = true;
  23668. }
  23669. needShadows = true;
  23670. }
  23671. }
  23672. lightIndex++;
  23673. if (lightIndex === maxSimultaneousLights)
  23674. break;
  23675. }
  23676. var caps = scene.getEngine().getCaps();
  23677. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  23678. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23679. needRebuild = true;
  23680. }
  23681. defines["SHADOWFULLFLOAT"] = true;
  23682. }
  23683. if (needRebuild) {
  23684. defines.rebuild();
  23685. }
  23686. return needNormals;
  23687. };
  23688. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  23689. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23690. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23691. if (!defines["LIGHT" + lightIndex]) {
  23692. break;
  23693. }
  23694. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23695. samplersList.push("shadowSampler" + lightIndex);
  23696. }
  23697. };
  23698. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23699. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23700. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23701. if (!defines["LIGHT" + lightIndex]) {
  23702. break;
  23703. }
  23704. if (lightIndex > 0) {
  23705. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23706. }
  23707. if (defines["SHADOW" + lightIndex]) {
  23708. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23709. }
  23710. if (defines["SHADOWPCF" + lightIndex]) {
  23711. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23712. }
  23713. if (defines["SHADOWVSM" + lightIndex]) {
  23714. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  23715. }
  23716. }
  23717. };
  23718. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23719. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23720. fallbacks.addCPUSkinningFallback(0, mesh);
  23721. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23722. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23723. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23726. }
  23727. }
  23728. };
  23729. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23730. if (defines["INSTANCES"]) {
  23731. attribs.push("world0");
  23732. attribs.push("world1");
  23733. attribs.push("world2");
  23734. attribs.push("world3");
  23735. }
  23736. };
  23737. // Bindings
  23738. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23739. var shadowGenerator = light.getShadowGenerator();
  23740. if (mesh.receiveShadows && shadowGenerator) {
  23741. if (!light.needCube()) {
  23742. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  23743. }
  23744. else {
  23745. if (!depthValuesAlreadySet) {
  23746. depthValuesAlreadySet = true;
  23747. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  23748. }
  23749. }
  23750. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  23751. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  23752. }
  23753. return depthValuesAlreadySet;
  23754. };
  23755. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23756. if (light instanceof BABYLON.PointLight) {
  23757. // Point Light
  23758. light.transferToEffect(effect, "vLightData" + lightIndex);
  23759. }
  23760. else if (light instanceof BABYLON.DirectionalLight) {
  23761. // Directional Light
  23762. light.transferToEffect(effect, "vLightData" + lightIndex);
  23763. }
  23764. else if (light instanceof BABYLON.SpotLight) {
  23765. // Spot Light
  23766. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  23767. }
  23768. else if (light instanceof BABYLON.HemisphericLight) {
  23769. // Hemispheric Light
  23770. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  23771. }
  23772. };
  23773. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23774. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23775. var lightIndex = 0;
  23776. var depthValuesAlreadySet = false;
  23777. for (var index = 0; index < scene.lights.length; index++) {
  23778. var light = scene.lights[index];
  23779. if (!light.isEnabled()) {
  23780. continue;
  23781. }
  23782. if (!light.canAffectMesh(mesh)) {
  23783. continue;
  23784. }
  23785. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23786. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23787. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  23788. if (defines["SPECULARTERM"]) {
  23789. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23790. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  23791. }
  23792. // Shadows
  23793. if (scene.shadowsEnabled) {
  23794. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  23795. }
  23796. lightIndex++;
  23797. if (lightIndex === maxSimultaneousLights)
  23798. break;
  23799. }
  23800. };
  23801. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23802. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23803. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23804. effect.setColor3("vFogColor", scene.fogColor);
  23805. }
  23806. };
  23807. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23808. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23809. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  23810. }
  23811. };
  23812. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23813. if (defines["LOGARITHMICDEPTH"]) {
  23814. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23815. }
  23816. };
  23817. MaterialHelper.BindClipPlane = function (effect, scene) {
  23818. if (scene.clipPlane) {
  23819. var clipPlane = scene.clipPlane;
  23820. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23821. }
  23822. };
  23823. return MaterialHelper;
  23824. })();
  23825. BABYLON.MaterialHelper = MaterialHelper;
  23826. })(BABYLON || (BABYLON = {}));
  23827. var BABYLON;
  23828. (function (BABYLON) {
  23829. var FresnelParameters = (function () {
  23830. function FresnelParameters() {
  23831. this.isEnabled = true;
  23832. this.leftColor = BABYLON.Color3.White();
  23833. this.rightColor = BABYLON.Color3.Black();
  23834. this.bias = 0;
  23835. this.power = 1;
  23836. }
  23837. FresnelParameters.prototype.clone = function () {
  23838. var newFresnelParameters = new FresnelParameters();
  23839. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  23840. return new FresnelParameters;
  23841. };
  23842. FresnelParameters.prototype.serialize = function () {
  23843. var serializationObject = {};
  23844. serializationObject.isEnabled = this.isEnabled;
  23845. serializationObject.leftColor = this.leftColor;
  23846. serializationObject.rightColor = this.rightColor;
  23847. serializationObject.bias = this.bias;
  23848. serializationObject.power = this.power;
  23849. return serializationObject;
  23850. };
  23851. FresnelParameters.Parse = function (parsedFresnelParameters) {
  23852. var fresnelParameters = new FresnelParameters();
  23853. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  23854. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  23855. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  23856. fresnelParameters.bias = parsedFresnelParameters.bias;
  23857. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  23858. return fresnelParameters;
  23859. };
  23860. return FresnelParameters;
  23861. })();
  23862. BABYLON.FresnelParameters = FresnelParameters;
  23863. })(BABYLON || (BABYLON = {}));
  23864. var BABYLON;
  23865. (function (BABYLON) {
  23866. var MaterialDefines = (function () {
  23867. function MaterialDefines() {
  23868. }
  23869. MaterialDefines.prototype.rebuild = function () {
  23870. if (this._keys) {
  23871. delete this._keys;
  23872. }
  23873. this._keys = Object.keys(this);
  23874. };
  23875. MaterialDefines.prototype.isEqual = function (other) {
  23876. if (this._keys.length !== other._keys.length) {
  23877. return false;
  23878. }
  23879. for (var index = 0; index < this._keys.length; index++) {
  23880. var prop = this._keys[index];
  23881. if (this[prop] !== other[prop]) {
  23882. return false;
  23883. }
  23884. }
  23885. return true;
  23886. };
  23887. MaterialDefines.prototype.cloneTo = function (other) {
  23888. if (this._keys.length !== other._keys.length) {
  23889. other._keys = this._keys.slice(0);
  23890. }
  23891. for (var index = 0; index < this._keys.length; index++) {
  23892. var prop = this._keys[index];
  23893. other[prop] = this[prop];
  23894. }
  23895. };
  23896. MaterialDefines.prototype.reset = function () {
  23897. for (var index = 0; index < this._keys.length; index++) {
  23898. var prop = this._keys[index];
  23899. if (typeof (this[prop]) === "number") {
  23900. this[prop] = 0;
  23901. }
  23902. else {
  23903. this[prop] = false;
  23904. }
  23905. }
  23906. };
  23907. MaterialDefines.prototype.toString = function () {
  23908. var result = "";
  23909. for (var index = 0; index < this._keys.length; index++) {
  23910. var prop = this._keys[index];
  23911. if (typeof (this[prop]) === "number") {
  23912. result += "#define " + prop + " " + this[prop] + "\n";
  23913. }
  23914. else if (this[prop]) {
  23915. result += "#define " + prop + "\n";
  23916. }
  23917. }
  23918. return result;
  23919. };
  23920. return MaterialDefines;
  23921. })();
  23922. BABYLON.MaterialDefines = MaterialDefines;
  23923. var Material = (function () {
  23924. function Material(name, scene, doNotAdd) {
  23925. this.name = name;
  23926. this.checkReadyOnEveryCall = false;
  23927. this.checkReadyOnlyOnce = false;
  23928. this.state = "";
  23929. this.alpha = 1.0;
  23930. this.backFaceCulling = true;
  23931. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23932. /**
  23933. * An event triggered when the material is disposed.
  23934. * @type {BABYLON.Observable}
  23935. */
  23936. this.onDisposeObservable = new BABYLON.Observable();
  23937. /**
  23938. * An event triggered when the material is compiled.
  23939. * @type {BABYLON.Observable}
  23940. */
  23941. this.onBindObservable = new BABYLON.Observable();
  23942. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23943. this.disableDepthWrite = false;
  23944. this.fogEnabled = true;
  23945. this.pointSize = 1.0;
  23946. this.zOffset = 0;
  23947. this._wasPreviouslyReady = false;
  23948. this._fillMode = Material.TriangleFillMode;
  23949. this.id = name;
  23950. this._scene = scene;
  23951. if (!doNotAdd) {
  23952. scene.materials.push(this);
  23953. }
  23954. }
  23955. Object.defineProperty(Material, "TriangleFillMode", {
  23956. get: function () {
  23957. return Material._TriangleFillMode;
  23958. },
  23959. enumerable: true,
  23960. configurable: true
  23961. });
  23962. Object.defineProperty(Material, "WireFrameFillMode", {
  23963. get: function () {
  23964. return Material._WireFrameFillMode;
  23965. },
  23966. enumerable: true,
  23967. configurable: true
  23968. });
  23969. Object.defineProperty(Material, "PointFillMode", {
  23970. get: function () {
  23971. return Material._PointFillMode;
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23977. get: function () {
  23978. return Material._ClockWiseSideOrientation;
  23979. },
  23980. enumerable: true,
  23981. configurable: true
  23982. });
  23983. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23984. get: function () {
  23985. return Material._CounterClockWiseSideOrientation;
  23986. },
  23987. enumerable: true,
  23988. configurable: true
  23989. });
  23990. Object.defineProperty(Material.prototype, "onDispose", {
  23991. set: function (callback) {
  23992. if (this._onDisposeObserver) {
  23993. this.onDisposeObservable.remove(this._onDisposeObserver);
  23994. }
  23995. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23996. },
  23997. enumerable: true,
  23998. configurable: true
  23999. });
  24000. Object.defineProperty(Material.prototype, "onBind", {
  24001. set: function (callback) {
  24002. if (this._onBindObserver) {
  24003. this.onBindObservable.remove(this._onBindObserver);
  24004. }
  24005. this._onBindObserver = this.onBindObservable.add(callback);
  24006. },
  24007. enumerable: true,
  24008. configurable: true
  24009. });
  24010. Object.defineProperty(Material.prototype, "wireframe", {
  24011. get: function () {
  24012. return this._fillMode === Material.WireFrameFillMode;
  24013. },
  24014. set: function (value) {
  24015. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24016. },
  24017. enumerable: true,
  24018. configurable: true
  24019. });
  24020. Object.defineProperty(Material.prototype, "pointsCloud", {
  24021. get: function () {
  24022. return this._fillMode === Material.PointFillMode;
  24023. },
  24024. set: function (value) {
  24025. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24026. },
  24027. enumerable: true,
  24028. configurable: true
  24029. });
  24030. Object.defineProperty(Material.prototype, "fillMode", {
  24031. get: function () {
  24032. return this._fillMode;
  24033. },
  24034. set: function (value) {
  24035. this._fillMode = value;
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. /**
  24041. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24042. * subclasses should override adding information pertainent to themselves
  24043. */
  24044. Material.prototype.toString = function (fullDetails) {
  24045. var ret = "Name: " + this.name;
  24046. if (fullDetails) {
  24047. }
  24048. return ret;
  24049. };
  24050. Object.defineProperty(Material.prototype, "isFrozen", {
  24051. get: function () {
  24052. return this.checkReadyOnlyOnce;
  24053. },
  24054. enumerable: true,
  24055. configurable: true
  24056. });
  24057. Material.prototype.freeze = function () {
  24058. this.checkReadyOnlyOnce = true;
  24059. };
  24060. Material.prototype.unfreeze = function () {
  24061. this.checkReadyOnlyOnce = false;
  24062. };
  24063. Material.prototype.isReady = function (mesh, useInstances) {
  24064. return true;
  24065. };
  24066. Material.prototype.getEffect = function () {
  24067. return this._effect;
  24068. };
  24069. Material.prototype.getScene = function () {
  24070. return this._scene;
  24071. };
  24072. Material.prototype.needAlphaBlending = function () {
  24073. return (this.alpha < 1.0);
  24074. };
  24075. Material.prototype.needAlphaTesting = function () {
  24076. return false;
  24077. };
  24078. Material.prototype.getAlphaTestTexture = function () {
  24079. return null;
  24080. };
  24081. Material.prototype.markDirty = function () {
  24082. this._wasPreviouslyReady = false;
  24083. };
  24084. Material.prototype._preBind = function () {
  24085. var engine = this._scene.getEngine();
  24086. engine.enableEffect(this._effect);
  24087. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24088. };
  24089. Material.prototype.bind = function (world, mesh) {
  24090. this._scene._cachedMaterial = this;
  24091. this.onBindObservable.notifyObservers(mesh);
  24092. if (this.disableDepthWrite) {
  24093. var engine = this._scene.getEngine();
  24094. this._cachedDepthWriteState = engine.getDepthWrite();
  24095. engine.setDepthWrite(false);
  24096. }
  24097. };
  24098. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24099. };
  24100. Material.prototype.unbind = function () {
  24101. if (this.disableDepthWrite) {
  24102. var engine = this._scene.getEngine();
  24103. engine.setDepthWrite(this._cachedDepthWriteState);
  24104. }
  24105. };
  24106. Material.prototype.clone = function (name) {
  24107. return null;
  24108. };
  24109. Material.prototype.getBindedMeshes = function () {
  24110. var result = new Array();
  24111. for (var index = 0; index < this._scene.meshes.length; index++) {
  24112. var mesh = this._scene.meshes[index];
  24113. if (mesh.material === this) {
  24114. result.push(mesh);
  24115. }
  24116. }
  24117. return result;
  24118. };
  24119. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24120. // Animations
  24121. this.getScene().stopAnimation(this);
  24122. // Remove from scene
  24123. var index = this._scene.materials.indexOf(this);
  24124. if (index >= 0) {
  24125. this._scene.materials.splice(index, 1);
  24126. }
  24127. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24128. if (forceDisposeEffect && this._effect) {
  24129. this._scene.getEngine()._releaseEffect(this._effect);
  24130. this._effect = null;
  24131. }
  24132. // Remove from meshes
  24133. for (index = 0; index < this._scene.meshes.length; index++) {
  24134. var mesh = this._scene.meshes[index];
  24135. if (mesh.material === this) {
  24136. mesh.material = null;
  24137. }
  24138. }
  24139. // Callback
  24140. this.onDisposeObservable.notifyObservers(this);
  24141. this.onDisposeObservable.clear();
  24142. this.onBindObservable.clear();
  24143. };
  24144. Material.prototype.serialize = function () {
  24145. return BABYLON.SerializationHelper.Serialize(this);
  24146. };
  24147. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24148. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24149. multiMaterial.id = parsedMultiMaterial.id;
  24150. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24151. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24152. var subMatId = parsedMultiMaterial.materials[matIndex];
  24153. if (subMatId) {
  24154. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24155. }
  24156. else {
  24157. multiMaterial.subMaterials.push(null);
  24158. }
  24159. }
  24160. return multiMaterial;
  24161. };
  24162. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24163. if (!parsedMaterial.customType) {
  24164. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24165. }
  24166. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24167. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24168. ;
  24169. };
  24170. Material._TriangleFillMode = 0;
  24171. Material._WireFrameFillMode = 1;
  24172. Material._PointFillMode = 2;
  24173. Material._ClockWiseSideOrientation = 0;
  24174. Material._CounterClockWiseSideOrientation = 1;
  24175. __decorate([
  24176. BABYLON.serialize()
  24177. ], Material.prototype, "id", void 0);
  24178. __decorate([
  24179. BABYLON.serialize()
  24180. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24181. __decorate([
  24182. BABYLON.serialize()
  24183. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24184. __decorate([
  24185. BABYLON.serialize()
  24186. ], Material.prototype, "state", void 0);
  24187. __decorate([
  24188. BABYLON.serialize()
  24189. ], Material.prototype, "alpha", void 0);
  24190. __decorate([
  24191. BABYLON.serialize()
  24192. ], Material.prototype, "backFaceCulling", void 0);
  24193. __decorate([
  24194. BABYLON.serialize()
  24195. ], Material.prototype, "sideOrientation", void 0);
  24196. __decorate([
  24197. BABYLON.serialize()
  24198. ], Material.prototype, "alphaMode", void 0);
  24199. __decorate([
  24200. BABYLON.serialize()
  24201. ], Material.prototype, "disableDepthWrite", void 0);
  24202. __decorate([
  24203. BABYLON.serialize()
  24204. ], Material.prototype, "fogEnabled", void 0);
  24205. __decorate([
  24206. BABYLON.serialize()
  24207. ], Material.prototype, "pointSize", void 0);
  24208. __decorate([
  24209. BABYLON.serialize()
  24210. ], Material.prototype, "zOffset", void 0);
  24211. __decorate([
  24212. BABYLON.serialize()
  24213. ], Material.prototype, "wireframe", null);
  24214. __decorate([
  24215. BABYLON.serialize()
  24216. ], Material.prototype, "pointsCloud", null);
  24217. __decorate([
  24218. BABYLON.serialize()
  24219. ], Material.prototype, "fillMode", null);
  24220. return Material;
  24221. })();
  24222. BABYLON.Material = Material;
  24223. })(BABYLON || (BABYLON = {}));
  24224. var BABYLON;
  24225. (function (BABYLON) {
  24226. var StandardMaterialDefines = (function (_super) {
  24227. __extends(StandardMaterialDefines, _super);
  24228. function StandardMaterialDefines() {
  24229. _super.call(this);
  24230. this.DIFFUSE = false;
  24231. this.AMBIENT = false;
  24232. this.OPACITY = false;
  24233. this.OPACITYRGB = false;
  24234. this.REFLECTION = false;
  24235. this.EMISSIVE = false;
  24236. this.SPECULAR = false;
  24237. this.BUMP = false;
  24238. this.PARALLAX = false;
  24239. this.PARALLAXOCCLUSION = false;
  24240. this.SPECULAROVERALPHA = false;
  24241. this.CLIPPLANE = false;
  24242. this.ALPHATEST = false;
  24243. this.ALPHAFROMDIFFUSE = false;
  24244. this.POINTSIZE = false;
  24245. this.FOG = false;
  24246. this.SPECULARTERM = false;
  24247. this.DIFFUSEFRESNEL = false;
  24248. this.OPACITYFRESNEL = false;
  24249. this.REFLECTIONFRESNEL = false;
  24250. this.REFRACTIONFRESNEL = false;
  24251. this.EMISSIVEFRESNEL = false;
  24252. this.FRESNEL = false;
  24253. this.NORMAL = false;
  24254. this.UV1 = false;
  24255. this.UV2 = false;
  24256. this.VERTEXCOLOR = false;
  24257. this.VERTEXALPHA = false;
  24258. this.NUM_BONE_INFLUENCERS = 0;
  24259. this.BonesPerMesh = 0;
  24260. this.INSTANCES = false;
  24261. this.GLOSSINESS = false;
  24262. this.ROUGHNESS = false;
  24263. this.EMISSIVEASILLUMINATION = false;
  24264. this.LINKEMISSIVEWITHDIFFUSE = false;
  24265. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24266. this.LIGHTMAP = false;
  24267. this.USELIGHTMAPASSHADOWMAP = false;
  24268. this.REFLECTIONMAP_3D = false;
  24269. this.REFLECTIONMAP_SPHERICAL = false;
  24270. this.REFLECTIONMAP_PLANAR = false;
  24271. this.REFLECTIONMAP_CUBIC = false;
  24272. this.REFLECTIONMAP_PROJECTION = false;
  24273. this.REFLECTIONMAP_SKYBOX = false;
  24274. this.REFLECTIONMAP_EXPLICIT = false;
  24275. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24276. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24277. this.INVERTCUBICMAP = false;
  24278. this.LOGARITHMICDEPTH = false;
  24279. this.REFRACTION = false;
  24280. this.REFRACTIONMAP_3D = false;
  24281. this.REFLECTIONOVERALPHA = false;
  24282. this.INVERTNORMALMAPX = false;
  24283. this.INVERTNORMALMAPY = false;
  24284. this.SHADOWFULLFLOAT = false;
  24285. this.CAMERACOLORGRADING = false;
  24286. this.CAMERACOLORCURVES = false;
  24287. this.rebuild();
  24288. }
  24289. return StandardMaterialDefines;
  24290. })(BABYLON.MaterialDefines);
  24291. var StandardMaterial = (function (_super) {
  24292. __extends(StandardMaterial, _super);
  24293. function StandardMaterial(name, scene) {
  24294. var _this = this;
  24295. _super.call(this, name, scene);
  24296. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24297. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24298. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24299. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24300. this.specularPower = 64;
  24301. this.useAlphaFromDiffuseTexture = false;
  24302. this.useEmissiveAsIllumination = false;
  24303. this.linkEmissiveWithDiffuse = false;
  24304. this.useReflectionFresnelFromSpecular = false;
  24305. this.useSpecularOverAlpha = false;
  24306. this.useReflectionOverAlpha = false;
  24307. this.disableLighting = false;
  24308. this.useParallax = false;
  24309. this.useParallaxOcclusion = false;
  24310. this.parallaxScaleBias = 0.05;
  24311. this.roughness = 0;
  24312. this.indexOfRefraction = 0.98;
  24313. this.invertRefractionY = true;
  24314. this.useLightmapAsShadowmap = false;
  24315. this.useGlossinessFromSpecularMapAlpha = false;
  24316. this.maxSimultaneousLights = 4;
  24317. /**
  24318. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24319. */
  24320. this.invertNormalMapX = false;
  24321. /**
  24322. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24323. */
  24324. this.invertNormalMapY = false;
  24325. /**
  24326. * Color Grading 2D Lookup Texture.
  24327. * This allows special effects like sepia, black and white to sixties rendering style.
  24328. */
  24329. this.cameraColorGradingTexture = null;
  24330. /**
  24331. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24332. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24333. * 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;
  24334. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24335. */
  24336. this.cameraColorCurves = null;
  24337. this._renderTargets = new BABYLON.SmartArray(16);
  24338. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24339. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24340. this._defines = new StandardMaterialDefines();
  24341. this._cachedDefines = new StandardMaterialDefines();
  24342. this._cachedDefines.BonesPerMesh = -1;
  24343. this.getRenderTargetTextures = function () {
  24344. _this._renderTargets.reset();
  24345. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24346. _this._renderTargets.push(_this.reflectionTexture);
  24347. }
  24348. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24349. _this._renderTargets.push(_this.refractionTexture);
  24350. }
  24351. return _this._renderTargets;
  24352. };
  24353. }
  24354. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24355. get: function () {
  24356. return this._useLogarithmicDepth;
  24357. },
  24358. set: function (value) {
  24359. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24360. },
  24361. enumerable: true,
  24362. configurable: true
  24363. });
  24364. StandardMaterial.prototype.needAlphaBlending = function () {
  24365. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24366. };
  24367. StandardMaterial.prototype.needAlphaTesting = function () {
  24368. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24369. };
  24370. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24371. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24372. };
  24373. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24374. return this.diffuseTexture;
  24375. };
  24376. // Methods
  24377. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24378. if (!mesh) {
  24379. return true;
  24380. }
  24381. if (this._defines.INSTANCES !== useInstances) {
  24382. return false;
  24383. }
  24384. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  24385. return true;
  24386. }
  24387. return false;
  24388. };
  24389. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  24390. if (this.isFrozen) {
  24391. if (this._wasPreviouslyReady) {
  24392. return true;
  24393. }
  24394. }
  24395. var scene = this.getScene();
  24396. if (!this.checkReadyOnEveryCall) {
  24397. if (this._renderId === scene.getRenderId()) {
  24398. if (this._checkCache(scene, mesh, useInstances)) {
  24399. return true;
  24400. }
  24401. }
  24402. }
  24403. var engine = scene.getEngine();
  24404. var needNormals = false;
  24405. var needUVs = false;
  24406. this._defines.reset();
  24407. // Textures
  24408. if (scene.texturesEnabled) {
  24409. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24410. if (!this.diffuseTexture.isReady()) {
  24411. return false;
  24412. }
  24413. else {
  24414. needUVs = true;
  24415. this._defines.DIFFUSE = true;
  24416. }
  24417. }
  24418. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24419. if (!this.ambientTexture.isReady()) {
  24420. return false;
  24421. }
  24422. else {
  24423. needUVs = true;
  24424. this._defines.AMBIENT = true;
  24425. }
  24426. }
  24427. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24428. if (!this.opacityTexture.isReady()) {
  24429. return false;
  24430. }
  24431. else {
  24432. needUVs = true;
  24433. this._defines.OPACITY = true;
  24434. if (this.opacityTexture.getAlphaFromRGB) {
  24435. this._defines.OPACITYRGB = true;
  24436. }
  24437. }
  24438. }
  24439. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24440. if (!this.reflectionTexture.isReady()) {
  24441. return false;
  24442. }
  24443. else {
  24444. needNormals = true;
  24445. this._defines.REFLECTION = true;
  24446. if (this.roughness > 0) {
  24447. this._defines.ROUGHNESS = true;
  24448. }
  24449. if (this.useReflectionOverAlpha) {
  24450. this._defines.REFLECTIONOVERALPHA = true;
  24451. }
  24452. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  24453. this._defines.INVERTCUBICMAP = true;
  24454. }
  24455. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  24456. switch (this.reflectionTexture.coordinatesMode) {
  24457. case BABYLON.Texture.CUBIC_MODE:
  24458. case BABYLON.Texture.INVCUBIC_MODE:
  24459. this._defines.REFLECTIONMAP_CUBIC = true;
  24460. break;
  24461. case BABYLON.Texture.EXPLICIT_MODE:
  24462. this._defines.REFLECTIONMAP_EXPLICIT = true;
  24463. break;
  24464. case BABYLON.Texture.PLANAR_MODE:
  24465. this._defines.REFLECTIONMAP_PLANAR = true;
  24466. break;
  24467. case BABYLON.Texture.PROJECTION_MODE:
  24468. this._defines.REFLECTIONMAP_PROJECTION = true;
  24469. break;
  24470. case BABYLON.Texture.SKYBOX_MODE:
  24471. this._defines.REFLECTIONMAP_SKYBOX = true;
  24472. break;
  24473. case BABYLON.Texture.SPHERICAL_MODE:
  24474. this._defines.REFLECTIONMAP_SPHERICAL = true;
  24475. break;
  24476. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  24477. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  24478. break;
  24479. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  24480. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  24481. break;
  24482. }
  24483. }
  24484. }
  24485. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24486. if (!this.emissiveTexture.isReady()) {
  24487. return false;
  24488. }
  24489. else {
  24490. needUVs = true;
  24491. this._defines.EMISSIVE = true;
  24492. }
  24493. }
  24494. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24495. if (!this.lightmapTexture.isReady()) {
  24496. return false;
  24497. }
  24498. else {
  24499. needUVs = true;
  24500. this._defines.LIGHTMAP = true;
  24501. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  24502. }
  24503. }
  24504. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24505. if (!this.specularTexture.isReady()) {
  24506. return false;
  24507. }
  24508. else {
  24509. needUVs = true;
  24510. this._defines.SPECULAR = true;
  24511. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  24512. }
  24513. }
  24514. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  24515. if (!this.bumpTexture.isReady()) {
  24516. return false;
  24517. }
  24518. else {
  24519. needUVs = true;
  24520. this._defines.BUMP = true;
  24521. if (this.useParallax) {
  24522. this._defines.PARALLAX = true;
  24523. if (this.useParallaxOcclusion) {
  24524. this._defines.PARALLAXOCCLUSION = true;
  24525. }
  24526. }
  24527. if (this.invertNormalMapX) {
  24528. this._defines.INVERTNORMALMAPX = true;
  24529. }
  24530. if (this.invertNormalMapY) {
  24531. this._defines.INVERTNORMALMAPY = true;
  24532. }
  24533. }
  24534. }
  24535. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24536. if (!this.refractionTexture.isReady()) {
  24537. return false;
  24538. }
  24539. else {
  24540. needUVs = true;
  24541. this._defines.REFRACTION = true;
  24542. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  24543. }
  24544. }
  24545. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24546. if (!this.cameraColorGradingTexture.isReady()) {
  24547. return false;
  24548. }
  24549. else {
  24550. this._defines.CAMERACOLORGRADING = true;
  24551. }
  24552. }
  24553. }
  24554. // Effect
  24555. if (scene.clipPlane) {
  24556. this._defines.CLIPPLANE = true;
  24557. }
  24558. if (engine.getAlphaTesting()) {
  24559. this._defines.ALPHATEST = true;
  24560. }
  24561. if (this._shouldUseAlphaFromDiffuseTexture()) {
  24562. this._defines.ALPHAFROMDIFFUSE = true;
  24563. }
  24564. if (this.useEmissiveAsIllumination) {
  24565. this._defines.EMISSIVEASILLUMINATION = true;
  24566. }
  24567. if (this.linkEmissiveWithDiffuse) {
  24568. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  24569. }
  24570. if (this.useLogarithmicDepth) {
  24571. this._defines.LOGARITHMICDEPTH = true;
  24572. }
  24573. if (this.cameraColorCurves) {
  24574. this._defines.CAMERACOLORCURVES = true;
  24575. }
  24576. // Point size
  24577. if (this.pointsCloud || scene.forcePointsCloud) {
  24578. this._defines.POINTSIZE = true;
  24579. }
  24580. // Fog
  24581. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24582. this._defines.FOG = true;
  24583. }
  24584. if (scene.lightsEnabled && !this.disableLighting) {
  24585. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  24586. }
  24587. if (StandardMaterial.FresnelEnabled) {
  24588. // Fresnel
  24589. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  24590. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  24591. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  24592. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  24593. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24594. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24595. this._defines.DIFFUSEFRESNEL = true;
  24596. }
  24597. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24598. this._defines.OPACITYFRESNEL = true;
  24599. }
  24600. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24601. this._defines.REFLECTIONFRESNEL = true;
  24602. if (this.useReflectionFresnelFromSpecular) {
  24603. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  24604. }
  24605. }
  24606. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24607. this._defines.REFRACTIONFRESNEL = true;
  24608. }
  24609. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24610. this._defines.EMISSIVEFRESNEL = true;
  24611. }
  24612. needNormals = true;
  24613. this._defines.FRESNEL = true;
  24614. }
  24615. }
  24616. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  24617. this._defines.SPECULAROVERALPHA = true;
  24618. }
  24619. // Attribs
  24620. if (mesh) {
  24621. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24622. this._defines.NORMAL = true;
  24623. }
  24624. if (needUVs) {
  24625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24626. this._defines.UV1 = true;
  24627. }
  24628. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24629. this._defines.UV2 = true;
  24630. }
  24631. }
  24632. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24633. this._defines.VERTEXCOLOR = true;
  24634. if (mesh.hasVertexAlpha) {
  24635. this._defines.VERTEXALPHA = true;
  24636. }
  24637. }
  24638. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24639. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  24640. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  24641. }
  24642. // Instances
  24643. if (useInstances) {
  24644. this._defines.INSTANCES = true;
  24645. }
  24646. }
  24647. // Get correct effect
  24648. if (!this._defines.isEqual(this._cachedDefines)) {
  24649. this._defines.cloneTo(this._cachedDefines);
  24650. scene.resetCachedMaterial();
  24651. // Fallbacks
  24652. var fallbacks = new BABYLON.EffectFallbacks();
  24653. if (this._defines.REFLECTION) {
  24654. fallbacks.addFallback(0, "REFLECTION");
  24655. }
  24656. if (this._defines.SPECULAR) {
  24657. fallbacks.addFallback(0, "SPECULAR");
  24658. }
  24659. if (this._defines.BUMP) {
  24660. fallbacks.addFallback(0, "BUMP");
  24661. }
  24662. if (this._defines.PARALLAX) {
  24663. fallbacks.addFallback(1, "PARALLAX");
  24664. }
  24665. if (this._defines.PARALLAXOCCLUSION) {
  24666. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  24667. }
  24668. if (this._defines.SPECULAROVERALPHA) {
  24669. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  24670. }
  24671. if (this._defines.FOG) {
  24672. fallbacks.addFallback(1, "FOG");
  24673. }
  24674. if (this._defines.POINTSIZE) {
  24675. fallbacks.addFallback(0, "POINTSIZE");
  24676. }
  24677. if (this._defines.LOGARITHMICDEPTH) {
  24678. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  24679. }
  24680. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  24681. if (this._defines.SPECULARTERM) {
  24682. fallbacks.addFallback(0, "SPECULARTERM");
  24683. }
  24684. if (this._defines.DIFFUSEFRESNEL) {
  24685. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  24686. }
  24687. if (this._defines.OPACITYFRESNEL) {
  24688. fallbacks.addFallback(2, "OPACITYFRESNEL");
  24689. }
  24690. if (this._defines.REFLECTIONFRESNEL) {
  24691. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  24692. }
  24693. if (this._defines.EMISSIVEFRESNEL) {
  24694. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  24695. }
  24696. if (this._defines.FRESNEL) {
  24697. fallbacks.addFallback(4, "FRESNEL");
  24698. }
  24699. //Attributes
  24700. var attribs = [BABYLON.VertexBuffer.PositionKind];
  24701. if (this._defines.NORMAL) {
  24702. attribs.push(BABYLON.VertexBuffer.NormalKind);
  24703. }
  24704. if (this._defines.UV1) {
  24705. attribs.push(BABYLON.VertexBuffer.UVKind);
  24706. }
  24707. if (this._defines.UV2) {
  24708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24709. }
  24710. if (this._defines.VERTEXCOLOR) {
  24711. attribs.push(BABYLON.VertexBuffer.ColorKind);
  24712. }
  24713. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  24714. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  24715. var shaderName = "default";
  24716. var join = this._defines.toString();
  24717. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  24718. "vFogInfos", "vFogColor", "pointSize",
  24719. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  24720. "mBones",
  24721. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  24722. "depthValues",
  24723. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  24724. "logarithmicDepthConstant"
  24725. ];
  24726. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  24727. if (this._defines.CAMERACOLORCURVES) {
  24728. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  24729. }
  24730. if (this._defines.CAMERACOLORGRADING) {
  24731. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  24732. }
  24733. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  24734. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  24735. }
  24736. if (!this._effect.isReady()) {
  24737. return false;
  24738. }
  24739. this._renderId = scene.getRenderId();
  24740. this._wasPreviouslyReady = true;
  24741. if (mesh) {
  24742. if (!mesh._materialDefines) {
  24743. mesh._materialDefines = new StandardMaterialDefines();
  24744. }
  24745. this._defines.cloneTo(mesh._materialDefines);
  24746. }
  24747. return true;
  24748. };
  24749. StandardMaterial.prototype.unbind = function () {
  24750. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  24751. this._effect.setTexture("reflection2DSampler", null);
  24752. }
  24753. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  24754. this._effect.setTexture("refraction2DSampler", null);
  24755. }
  24756. _super.prototype.unbind.call(this);
  24757. };
  24758. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24759. this._effect.setMatrix("world", world);
  24760. };
  24761. StandardMaterial.prototype.bind = function (world, mesh) {
  24762. var scene = this.getScene();
  24763. // Matrices
  24764. this.bindOnlyWorldMatrix(world);
  24765. // Bones
  24766. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  24767. if (scene.getCachedMaterial() !== this) {
  24768. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24769. if (StandardMaterial.FresnelEnabled) {
  24770. // Fresnel
  24771. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  24772. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  24773. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  24774. }
  24775. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  24776. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  24777. }
  24778. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  24779. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  24780. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  24781. }
  24782. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  24783. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  24784. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  24785. }
  24786. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  24787. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  24788. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  24789. }
  24790. }
  24791. // Textures
  24792. if (scene.texturesEnabled) {
  24793. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  24794. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  24795. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  24796. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  24797. }
  24798. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  24799. this._effect.setTexture("ambientSampler", this.ambientTexture);
  24800. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  24801. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  24802. }
  24803. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  24804. this._effect.setTexture("opacitySampler", this.opacityTexture);
  24805. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  24806. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  24807. }
  24808. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  24809. if (this.reflectionTexture.isCube) {
  24810. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  24811. }
  24812. else {
  24813. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  24814. }
  24815. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  24816. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  24817. }
  24818. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  24819. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  24820. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  24821. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  24822. }
  24823. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  24824. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  24825. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  24826. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  24827. }
  24828. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  24829. this._effect.setTexture("specularSampler", this.specularTexture);
  24830. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  24831. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  24832. }
  24833. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  24834. this._effect.setTexture("bumpSampler", this.bumpTexture);
  24835. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  24836. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  24837. }
  24838. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  24839. var depth = 1.0;
  24840. if (this.refractionTexture.isCube) {
  24841. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  24842. }
  24843. else {
  24844. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  24845. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  24846. if (this.refractionTexture.depth) {
  24847. depth = this.refractionTexture.depth;
  24848. }
  24849. }
  24850. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  24851. }
  24852. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  24853. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  24854. }
  24855. }
  24856. // Clip plane
  24857. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  24858. // Point size
  24859. if (this.pointsCloud) {
  24860. this._effect.setFloat("pointSize", this.pointSize);
  24861. }
  24862. // Colors
  24863. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  24864. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  24865. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  24866. if (this._defines.SPECULARTERM) {
  24867. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  24868. }
  24869. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  24870. }
  24871. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  24872. // Diffuse
  24873. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  24874. // Lights
  24875. if (scene.lightsEnabled && !this.disableLighting) {
  24876. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  24877. }
  24878. // View
  24879. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  24880. this._effect.setMatrix("view", scene.getViewMatrix());
  24881. }
  24882. // Fog
  24883. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  24884. // Log. depth
  24885. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  24886. // Color Curves
  24887. if (this.cameraColorCurves) {
  24888. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  24889. }
  24890. }
  24891. _super.prototype.bind.call(this, world, mesh);
  24892. };
  24893. StandardMaterial.prototype.getAnimatables = function () {
  24894. var results = [];
  24895. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  24896. results.push(this.diffuseTexture);
  24897. }
  24898. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  24899. results.push(this.ambientTexture);
  24900. }
  24901. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  24902. results.push(this.opacityTexture);
  24903. }
  24904. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  24905. results.push(this.reflectionTexture);
  24906. }
  24907. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  24908. results.push(this.emissiveTexture);
  24909. }
  24910. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  24911. results.push(this.specularTexture);
  24912. }
  24913. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  24914. results.push(this.bumpTexture);
  24915. }
  24916. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  24917. results.push(this.lightmapTexture);
  24918. }
  24919. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  24920. results.push(this.refractionTexture);
  24921. }
  24922. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  24923. results.push(this.cameraColorGradingTexture);
  24924. }
  24925. return results;
  24926. };
  24927. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24928. if (forceDisposeTextures) {
  24929. if (this.diffuseTexture) {
  24930. this.diffuseTexture.dispose();
  24931. }
  24932. if (this.ambientTexture) {
  24933. this.ambientTexture.dispose();
  24934. }
  24935. if (this.opacityTexture) {
  24936. this.opacityTexture.dispose();
  24937. }
  24938. if (this.reflectionTexture) {
  24939. this.reflectionTexture.dispose();
  24940. }
  24941. if (this.emissiveTexture) {
  24942. this.emissiveTexture.dispose();
  24943. }
  24944. if (this.specularTexture) {
  24945. this.specularTexture.dispose();
  24946. }
  24947. if (this.bumpTexture) {
  24948. this.bumpTexture.dispose();
  24949. }
  24950. if (this.lightmapTexture) {
  24951. this.lightmapTexture.dispose();
  24952. }
  24953. if (this.refractionTexture) {
  24954. this.refractionTexture.dispose();
  24955. }
  24956. if (this.cameraColorGradingTexture) {
  24957. this.cameraColorGradingTexture.dispose();
  24958. }
  24959. }
  24960. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  24961. };
  24962. StandardMaterial.prototype.clone = function (name) {
  24963. var _this = this;
  24964. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  24965. };
  24966. StandardMaterial.prototype.serialize = function () {
  24967. return BABYLON.SerializationHelper.Serialize(this);
  24968. };
  24969. // Statics
  24970. StandardMaterial.Parse = function (source, scene, rootUrl) {
  24971. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  24972. };
  24973. // Flags used to enable or disable a type of texture for all Standard Materials
  24974. StandardMaterial.DiffuseTextureEnabled = true;
  24975. StandardMaterial.AmbientTextureEnabled = true;
  24976. StandardMaterial.OpacityTextureEnabled = true;
  24977. StandardMaterial.ReflectionTextureEnabled = true;
  24978. StandardMaterial.EmissiveTextureEnabled = true;
  24979. StandardMaterial.SpecularTextureEnabled = true;
  24980. StandardMaterial.BumpTextureEnabled = true;
  24981. StandardMaterial.FresnelEnabled = true;
  24982. StandardMaterial.LightmapTextureEnabled = true;
  24983. StandardMaterial.RefractionTextureEnabled = true;
  24984. StandardMaterial.ColorGradingTextureEnabled = true;
  24985. __decorate([
  24986. BABYLON.serializeAsTexture()
  24987. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  24988. __decorate([
  24989. BABYLON.serializeAsTexture()
  24990. ], StandardMaterial.prototype, "ambientTexture", void 0);
  24991. __decorate([
  24992. BABYLON.serializeAsTexture()
  24993. ], StandardMaterial.prototype, "opacityTexture", void 0);
  24994. __decorate([
  24995. BABYLON.serializeAsTexture()
  24996. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  24997. __decorate([
  24998. BABYLON.serializeAsTexture()
  24999. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25000. __decorate([
  25001. BABYLON.serializeAsTexture()
  25002. ], StandardMaterial.prototype, "specularTexture", void 0);
  25003. __decorate([
  25004. BABYLON.serializeAsTexture()
  25005. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25006. __decorate([
  25007. BABYLON.serializeAsTexture()
  25008. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25009. __decorate([
  25010. BABYLON.serializeAsTexture()
  25011. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25012. __decorate([
  25013. BABYLON.serializeAsColor3("ambient")
  25014. ], StandardMaterial.prototype, "ambientColor", void 0);
  25015. __decorate([
  25016. BABYLON.serializeAsColor3("diffuse")
  25017. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25018. __decorate([
  25019. BABYLON.serializeAsColor3("specular")
  25020. ], StandardMaterial.prototype, "specularColor", void 0);
  25021. __decorate([
  25022. BABYLON.serializeAsColor3("emissive")
  25023. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25024. __decorate([
  25025. BABYLON.serialize()
  25026. ], StandardMaterial.prototype, "specularPower", void 0);
  25027. __decorate([
  25028. BABYLON.serialize()
  25029. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25030. __decorate([
  25031. BABYLON.serialize()
  25032. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25033. __decorate([
  25034. BABYLON.serialize()
  25035. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25036. __decorate([
  25037. BABYLON.serialize()
  25038. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25039. __decorate([
  25040. BABYLON.serialize()
  25041. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25042. __decorate([
  25043. BABYLON.serialize()
  25044. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25045. __decorate([
  25046. BABYLON.serialize()
  25047. ], StandardMaterial.prototype, "disableLighting", void 0);
  25048. __decorate([
  25049. BABYLON.serialize()
  25050. ], StandardMaterial.prototype, "useParallax", void 0);
  25051. __decorate([
  25052. BABYLON.serialize()
  25053. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25054. __decorate([
  25055. BABYLON.serialize()
  25056. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25057. __decorate([
  25058. BABYLON.serialize()
  25059. ], StandardMaterial.prototype, "roughness", void 0);
  25060. __decorate([
  25061. BABYLON.serialize()
  25062. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25063. __decorate([
  25064. BABYLON.serialize()
  25065. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25066. __decorate([
  25067. BABYLON.serialize()
  25068. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25069. __decorate([
  25070. BABYLON.serializeAsFresnelParameters()
  25071. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25072. __decorate([
  25073. BABYLON.serializeAsFresnelParameters()
  25074. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25075. __decorate([
  25076. BABYLON.serializeAsFresnelParameters()
  25077. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25078. __decorate([
  25079. BABYLON.serializeAsFresnelParameters()
  25080. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25081. __decorate([
  25082. BABYLON.serializeAsFresnelParameters()
  25083. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25084. __decorate([
  25085. BABYLON.serialize()
  25086. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25087. __decorate([
  25088. BABYLON.serialize()
  25089. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25090. __decorate([
  25091. BABYLON.serialize()
  25092. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25093. __decorate([
  25094. BABYLON.serialize()
  25095. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25096. __decorate([
  25097. BABYLON.serializeAsTexture()
  25098. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25099. __decorate([
  25100. BABYLON.serializeAsColorCurves()
  25101. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25102. __decorate([
  25103. BABYLON.serialize()
  25104. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25105. return StandardMaterial;
  25106. })(BABYLON.Material);
  25107. BABYLON.StandardMaterial = StandardMaterial;
  25108. })(BABYLON || (BABYLON = {}));
  25109. var BABYLON;
  25110. (function (BABYLON) {
  25111. var MultiMaterial = (function (_super) {
  25112. __extends(MultiMaterial, _super);
  25113. function MultiMaterial(name, scene) {
  25114. _super.call(this, name, scene, true);
  25115. this.subMaterials = new Array();
  25116. scene.multiMaterials.push(this);
  25117. }
  25118. // Properties
  25119. MultiMaterial.prototype.getSubMaterial = function (index) {
  25120. if (index < 0 || index >= this.subMaterials.length) {
  25121. return this.getScene().defaultMaterial;
  25122. }
  25123. return this.subMaterials[index];
  25124. };
  25125. // Methods
  25126. MultiMaterial.prototype.isReady = function (mesh) {
  25127. for (var index = 0; index < this.subMaterials.length; index++) {
  25128. var subMaterial = this.subMaterials[index];
  25129. if (subMaterial) {
  25130. if (!this.subMaterials[index].isReady(mesh)) {
  25131. return false;
  25132. }
  25133. }
  25134. }
  25135. return true;
  25136. };
  25137. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25138. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25139. for (var index = 0; index < this.subMaterials.length; index++) {
  25140. var subMaterial = null;
  25141. if (cloneChildren) {
  25142. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25143. }
  25144. else {
  25145. subMaterial = this.subMaterials[index];
  25146. }
  25147. newMultiMaterial.subMaterials.push(subMaterial);
  25148. }
  25149. return newMultiMaterial;
  25150. };
  25151. MultiMaterial.prototype.serialize = function () {
  25152. var serializationObject = {};
  25153. serializationObject.name = this.name;
  25154. serializationObject.id = this.id;
  25155. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25156. serializationObject.materials = [];
  25157. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25158. var subMat = this.subMaterials[matIndex];
  25159. if (subMat) {
  25160. serializationObject.materials.push(subMat.id);
  25161. }
  25162. else {
  25163. serializationObject.materials.push(null);
  25164. }
  25165. }
  25166. return serializationObject;
  25167. };
  25168. return MultiMaterial;
  25169. })(BABYLON.Material);
  25170. BABYLON.MultiMaterial = MultiMaterial;
  25171. })(BABYLON || (BABYLON = {}));
  25172. var BABYLON;
  25173. (function (BABYLON) {
  25174. var SceneLoader = (function () {
  25175. function SceneLoader() {
  25176. }
  25177. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25178. get: function () {
  25179. return 0;
  25180. },
  25181. enumerable: true,
  25182. configurable: true
  25183. });
  25184. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25185. get: function () {
  25186. return 1;
  25187. },
  25188. enumerable: true,
  25189. configurable: true
  25190. });
  25191. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25192. get: function () {
  25193. return 2;
  25194. },
  25195. enumerable: true,
  25196. configurable: true
  25197. });
  25198. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25199. get: function () {
  25200. return 3;
  25201. },
  25202. enumerable: true,
  25203. configurable: true
  25204. });
  25205. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25206. get: function () {
  25207. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25208. },
  25209. set: function (value) {
  25210. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25211. },
  25212. enumerable: true,
  25213. configurable: true
  25214. });
  25215. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25216. get: function () {
  25217. return SceneLoader._ShowLoadingScreen;
  25218. },
  25219. set: function (value) {
  25220. SceneLoader._ShowLoadingScreen = value;
  25221. },
  25222. enumerable: true,
  25223. configurable: true
  25224. });
  25225. Object.defineProperty(SceneLoader, "loggingLevel", {
  25226. get: function () {
  25227. return SceneLoader._loggingLevel;
  25228. },
  25229. set: function (value) {
  25230. SceneLoader._loggingLevel = value;
  25231. },
  25232. enumerable: true,
  25233. configurable: true
  25234. });
  25235. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25236. var dotPosition = sceneFilename.lastIndexOf(".");
  25237. var queryStringPosition = sceneFilename.indexOf("?");
  25238. if (queryStringPosition === -1) {
  25239. queryStringPosition = sceneFilename.length;
  25240. }
  25241. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25242. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25243. var plugin = this._registeredPlugins[index];
  25244. if (plugin.extensions.indexOf(extension) !== -1) {
  25245. return plugin;
  25246. }
  25247. }
  25248. return this._registeredPlugins[0];
  25249. };
  25250. // Public functions
  25251. SceneLoader.GetPluginForExtension = function (extension) {
  25252. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25253. var plugin = this._registeredPlugins[index];
  25254. if (plugin.extensions.indexOf(extension) !== -1) {
  25255. return plugin;
  25256. }
  25257. }
  25258. return null;
  25259. };
  25260. SceneLoader.RegisterPlugin = function (plugin) {
  25261. plugin.extensions = plugin.extensions.toLowerCase();
  25262. SceneLoader._registeredPlugins.push(plugin);
  25263. };
  25264. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25265. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25266. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25267. return;
  25268. }
  25269. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25270. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25271. return;
  25272. }
  25273. var loadingToken = {};
  25274. scene._addPendingData(loadingToken);
  25275. var manifestChecked = function (success) {
  25276. scene.database = database;
  25277. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25278. var importMeshFromData = function (data) {
  25279. var meshes = [];
  25280. var particleSystems = [];
  25281. var skeletons = [];
  25282. try {
  25283. if (plugin.importMesh) {
  25284. var syncedPlugin = plugin;
  25285. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25286. if (onerror) {
  25287. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25288. }
  25289. scene._removePendingData(loadingToken);
  25290. return;
  25291. }
  25292. if (onsuccess) {
  25293. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25294. onsuccess(meshes, particleSystems, skeletons);
  25295. scene._removePendingData(loadingToken);
  25296. }
  25297. }
  25298. else {
  25299. var asyncedPlugin = plugin;
  25300. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25301. if (onsuccess) {
  25302. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25303. onsuccess(meshes, particleSystems, skeletons);
  25304. scene._removePendingData(loadingToken);
  25305. }
  25306. }, function () {
  25307. if (onerror) {
  25308. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25309. }
  25310. scene._removePendingData(loadingToken);
  25311. });
  25312. }
  25313. }
  25314. catch (e) {
  25315. if (onerror) {
  25316. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25317. }
  25318. scene._removePendingData(loadingToken);
  25319. }
  25320. };
  25321. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25322. // Direct load
  25323. importMeshFromData(sceneFilename.substr(5));
  25324. return;
  25325. }
  25326. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25327. importMeshFromData(data);
  25328. }, progressCallBack, database);
  25329. };
  25330. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25331. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25332. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25333. }
  25334. else {
  25335. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25336. manifestChecked(true);
  25337. }
  25338. };
  25339. /**
  25340. * Load a scene
  25341. * @param rootUrl a string that defines the root url for scene and resources
  25342. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25343. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25344. */
  25345. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25346. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25347. };
  25348. /**
  25349. * Append a scene
  25350. * @param rootUrl a string that defines the root url for scene and resources
  25351. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25352. * @param scene is the instance of BABYLON.Scene to append to
  25353. */
  25354. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25355. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25356. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25357. return;
  25358. }
  25359. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25360. var database;
  25361. var loadingToken = {};
  25362. scene._addPendingData(loadingToken);
  25363. if (SceneLoader.ShowLoadingScreen) {
  25364. scene.getEngine().displayLoadingUI();
  25365. }
  25366. var loadSceneFromData = function (data) {
  25367. scene.database = database;
  25368. if (plugin.load) {
  25369. var syncedPlugin = plugin;
  25370. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25371. if (onerror) {
  25372. onerror(scene);
  25373. }
  25374. scene._removePendingData(loadingToken);
  25375. scene.getEngine().hideLoadingUI();
  25376. return;
  25377. }
  25378. if (onsuccess) {
  25379. onsuccess(scene);
  25380. }
  25381. scene._removePendingData(loadingToken);
  25382. }
  25383. else {
  25384. var asyncedPlugin = plugin;
  25385. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  25386. if (onsuccess) {
  25387. onsuccess(scene);
  25388. }
  25389. }, function () {
  25390. if (onerror) {
  25391. onerror(scene);
  25392. }
  25393. scene._removePendingData(loadingToken);
  25394. scene.getEngine().hideLoadingUI();
  25395. });
  25396. }
  25397. if (SceneLoader.ShowLoadingScreen) {
  25398. scene.executeWhenReady(function () {
  25399. scene.getEngine().hideLoadingUI();
  25400. });
  25401. }
  25402. };
  25403. var manifestChecked = function (success) {
  25404. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  25405. };
  25406. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25407. // Direct load
  25408. loadSceneFromData(sceneFilename.substr(5));
  25409. return;
  25410. }
  25411. if (rootUrl.indexOf("file:") === -1) {
  25412. if (scene.getEngine().enableOfflineSupport) {
  25413. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25414. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25415. }
  25416. else {
  25417. manifestChecked(true);
  25418. }
  25419. }
  25420. else {
  25421. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  25422. }
  25423. };
  25424. // Flags
  25425. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  25426. SceneLoader._ShowLoadingScreen = true;
  25427. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  25428. // Members
  25429. SceneLoader._registeredPlugins = new Array();
  25430. return SceneLoader;
  25431. })();
  25432. BABYLON.SceneLoader = SceneLoader;
  25433. ;
  25434. })(BABYLON || (BABYLON = {}));
  25435. var BABYLON;
  25436. (function (BABYLON) {
  25437. var Internals;
  25438. (function (Internals) {
  25439. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  25440. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25441. var parsedMaterial = parsedData.materials[index];
  25442. if (parsedMaterial.id === id) {
  25443. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25444. }
  25445. }
  25446. return null;
  25447. };
  25448. var isDescendantOf = function (mesh, names, hierarchyIds) {
  25449. names = (names instanceof Array) ? names : [names];
  25450. for (var i in names) {
  25451. if (mesh.name === names[i]) {
  25452. hierarchyIds.push(mesh.id);
  25453. return true;
  25454. }
  25455. }
  25456. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  25457. hierarchyIds.push(mesh.id);
  25458. return true;
  25459. }
  25460. return false;
  25461. };
  25462. var logOperation = function (operation, producer) {
  25463. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  25464. };
  25465. BABYLON.SceneLoader.RegisterPlugin({
  25466. extensions: ".babylon",
  25467. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  25468. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25469. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25470. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25471. // and avoid problems with multiple concurrent .babylon loads.
  25472. var log = "importMesh has failed JSON parse";
  25473. try {
  25474. var parsedData = JSON.parse(data);
  25475. log = "";
  25476. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25477. var loadedSkeletonsIds = [];
  25478. var loadedMaterialsIds = [];
  25479. var hierarchyIds = [];
  25480. var index;
  25481. var cache;
  25482. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25483. var parsedMesh = parsedData.meshes[index];
  25484. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  25485. if (meshesNames instanceof Array) {
  25486. // Remove found mesh name from list.
  25487. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  25488. }
  25489. //Geometry?
  25490. if (parsedMesh.geometryId) {
  25491. //does the file contain geometries?
  25492. if (parsedData.geometries) {
  25493. //find the correct geometry and add it to the scene
  25494. var found = false;
  25495. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  25496. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  25497. return;
  25498. }
  25499. else {
  25500. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  25501. if (parsedGeometryData.id === parsedMesh.geometryId) {
  25502. switch (geometryType) {
  25503. case "boxes":
  25504. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  25505. break;
  25506. case "spheres":
  25507. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  25508. break;
  25509. case "cylinders":
  25510. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  25511. break;
  25512. case "toruses":
  25513. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  25514. break;
  25515. case "grounds":
  25516. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  25517. break;
  25518. case "planes":
  25519. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  25520. break;
  25521. case "torusKnots":
  25522. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  25523. break;
  25524. case "vertexData":
  25525. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  25526. break;
  25527. }
  25528. found = true;
  25529. }
  25530. });
  25531. }
  25532. });
  25533. if (!found) {
  25534. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  25535. }
  25536. }
  25537. }
  25538. // Material ?
  25539. if (parsedMesh.materialId) {
  25540. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  25541. if (!materialFound && parsedData.multiMaterials) {
  25542. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  25543. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  25544. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  25545. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  25546. var subMatId = parsedMultiMaterial.materials[matIndex];
  25547. loadedMaterialsIds.push(subMatId);
  25548. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  25549. log += "\n\tMaterial " + mat.toString(fullDetails);
  25550. }
  25551. loadedMaterialsIds.push(parsedMultiMaterial.id);
  25552. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25553. materialFound = true;
  25554. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  25555. break;
  25556. }
  25557. }
  25558. }
  25559. if (!materialFound) {
  25560. loadedMaterialsIds.push(parsedMesh.materialId);
  25561. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  25562. if (!mat) {
  25563. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  25564. }
  25565. else {
  25566. log += "\n\tMaterial " + mat.toString(fullDetails);
  25567. }
  25568. }
  25569. }
  25570. // Skeleton ?
  25571. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  25572. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  25573. if (!skeletonAlreadyLoaded) {
  25574. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  25575. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  25576. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  25577. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25578. skeletons.push(skeleton);
  25579. loadedSkeletonsIds.push(parsedSkeleton.id);
  25580. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  25581. }
  25582. }
  25583. }
  25584. }
  25585. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25586. meshes.push(mesh);
  25587. log += "\n\tMesh " + mesh.toString(fullDetails);
  25588. }
  25589. }
  25590. // Connecting parents
  25591. var currentMesh;
  25592. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25593. currentMesh = scene.meshes[index];
  25594. if (currentMesh._waitingParentId) {
  25595. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  25596. currentMesh._waitingParentId = undefined;
  25597. }
  25598. }
  25599. // freeze and compute world matrix application
  25600. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25601. currentMesh = scene.meshes[index];
  25602. if (currentMesh._waitingFreezeWorldMatrix) {
  25603. currentMesh.freezeWorldMatrix();
  25604. currentMesh._waitingFreezeWorldMatrix = undefined;
  25605. }
  25606. else {
  25607. currentMesh.computeWorldMatrix(true);
  25608. }
  25609. }
  25610. // Particles
  25611. if (parsedData.particleSystems) {
  25612. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25613. var parsedParticleSystem = parsedData.particleSystems[index];
  25614. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  25615. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  25616. }
  25617. }
  25618. }
  25619. return true;
  25620. }
  25621. catch (err) {
  25622. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  25623. log = null;
  25624. throw err;
  25625. }
  25626. finally {
  25627. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25628. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25629. }
  25630. }
  25631. },
  25632. load: function (scene, data, rootUrl) {
  25633. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  25634. // when SceneLoader.debugLogging = true (default), or exception encountered.
  25635. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  25636. // and avoid problems with multiple concurrent .babylon loads.
  25637. var log = "importScene has failed JSON parse";
  25638. try {
  25639. var parsedData = JSON.parse(data);
  25640. log = "";
  25641. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  25642. // Scene
  25643. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  25644. scene.autoClear = parsedData.autoClear;
  25645. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  25646. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  25647. if (parsedData.gravity) {
  25648. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  25649. }
  25650. // Fog
  25651. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  25652. scene.fogMode = parsedData.fogMode;
  25653. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  25654. scene.fogStart = parsedData.fogStart;
  25655. scene.fogEnd = parsedData.fogEnd;
  25656. scene.fogDensity = parsedData.fogDensity;
  25657. log += "\tFog mode for scene: ";
  25658. switch (scene.fogMode) {
  25659. // getters not compiling, so using hardcoded
  25660. case 1:
  25661. log += "exp\n";
  25662. break;
  25663. case 2:
  25664. log += "exp2\n";
  25665. break;
  25666. case 3:
  25667. log += "linear\n";
  25668. break;
  25669. }
  25670. }
  25671. //Physics
  25672. if (parsedData.physicsEnabled) {
  25673. var physicsPlugin;
  25674. if (parsedData.physicsEngine === "cannon") {
  25675. physicsPlugin = new BABYLON.CannonJSPlugin();
  25676. }
  25677. else if (parsedData.physicsEngine === "oimo") {
  25678. physicsPlugin = new BABYLON.OimoJSPlugin();
  25679. }
  25680. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  25681. //else - default engine, which is currently oimo
  25682. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  25683. scene.enablePhysics(physicsGravity, physicsPlugin);
  25684. }
  25685. //collisions, if defined. otherwise, default is true
  25686. if (parsedData.collisionsEnabled != undefined) {
  25687. scene.collisionsEnabled = parsedData.collisionsEnabled;
  25688. }
  25689. scene.workerCollisions = !!parsedData.workerCollisions;
  25690. var index;
  25691. var cache;
  25692. // Lights
  25693. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  25694. var parsedLight = parsedData.lights[index];
  25695. var light = BABYLON.Light.Parse(parsedLight, scene);
  25696. log += (index === 0 ? "\n\tLights:" : "");
  25697. log += "\n\t\t" + light.toString(fullDetails);
  25698. }
  25699. // Animations
  25700. if (parsedData.animations) {
  25701. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  25702. var parsedAnimation = parsedData.animations[index];
  25703. var animation = BABYLON.Animation.Parse(parsedAnimation);
  25704. scene.animations.push(animation);
  25705. log += (index === 0 ? "\n\tAnimations:" : "");
  25706. log += "\n\t\t" + animation.toString(fullDetails);
  25707. }
  25708. }
  25709. if (parsedData.autoAnimate) {
  25710. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  25711. }
  25712. // Materials
  25713. if (parsedData.materials) {
  25714. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  25715. var parsedMaterial = parsedData.materials[index];
  25716. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  25717. log += (index === 0 ? "\n\tMaterials:" : "");
  25718. log += "\n\t\t" + mat.toString(fullDetails);
  25719. }
  25720. }
  25721. if (parsedData.multiMaterials) {
  25722. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  25723. var parsedMultiMaterial = parsedData.multiMaterials[index];
  25724. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  25725. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  25726. log += "\n\t\t" + mmat.toString(fullDetails);
  25727. }
  25728. }
  25729. // Skeletons
  25730. if (parsedData.skeletons) {
  25731. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  25732. var parsedSkeleton = parsedData.skeletons[index];
  25733. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  25734. log += (index === 0 ? "\n\tSkeletons:" : "");
  25735. log += "\n\t\t" + skeleton.toString(fullDetails);
  25736. }
  25737. }
  25738. // Geometries
  25739. var geometries = parsedData.geometries;
  25740. if (geometries) {
  25741. // Boxes
  25742. var boxes = geometries.boxes;
  25743. if (boxes) {
  25744. for (index = 0, cache = boxes.length; index < cache; index++) {
  25745. var parsedBox = boxes[index];
  25746. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  25747. }
  25748. }
  25749. // Spheres
  25750. var spheres = geometries.spheres;
  25751. if (spheres) {
  25752. for (index = 0, cache = spheres.length; index < cache; index++) {
  25753. var parsedSphere = spheres[index];
  25754. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  25755. }
  25756. }
  25757. // Cylinders
  25758. var cylinders = geometries.cylinders;
  25759. if (cylinders) {
  25760. for (index = 0, cache = cylinders.length; index < cache; index++) {
  25761. var parsedCylinder = cylinders[index];
  25762. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  25763. }
  25764. }
  25765. // Toruses
  25766. var toruses = geometries.toruses;
  25767. if (toruses) {
  25768. for (index = 0, cache = toruses.length; index < cache; index++) {
  25769. var parsedTorus = toruses[index];
  25770. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  25771. }
  25772. }
  25773. // Grounds
  25774. var grounds = geometries.grounds;
  25775. if (grounds) {
  25776. for (index = 0, cache = grounds.length; index < cache; index++) {
  25777. var parsedGround = grounds[index];
  25778. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  25779. }
  25780. }
  25781. // Planes
  25782. var planes = geometries.planes;
  25783. if (planes) {
  25784. for (index = 0, cache = planes.length; index < cache; index++) {
  25785. var parsedPlane = planes[index];
  25786. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  25787. }
  25788. }
  25789. // TorusKnots
  25790. var torusKnots = geometries.torusKnots;
  25791. if (torusKnots) {
  25792. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  25793. var parsedTorusKnot = torusKnots[index];
  25794. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  25795. }
  25796. }
  25797. // VertexData
  25798. var vertexData = geometries.vertexData;
  25799. if (vertexData) {
  25800. for (index = 0, cache = vertexData.length; index < cache; index++) {
  25801. var parsedVertexData = vertexData[index];
  25802. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  25803. }
  25804. }
  25805. }
  25806. // Meshes
  25807. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  25808. var parsedMesh = parsedData.meshes[index];
  25809. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  25810. log += (index === 0 ? "\n\tMeshes:" : "");
  25811. log += "\n\t\t" + mesh.toString(fullDetails);
  25812. }
  25813. // Cameras
  25814. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  25815. var parsedCamera = parsedData.cameras[index];
  25816. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  25817. log += (index === 0 ? "\n\tCameras:" : "");
  25818. log += "\n\t\t" + camera.toString(fullDetails);
  25819. }
  25820. if (parsedData.activeCameraID) {
  25821. scene.setActiveCameraByID(parsedData.activeCameraID);
  25822. }
  25823. // Browsing all the graph to connect the dots
  25824. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  25825. var camera = scene.cameras[index];
  25826. if (camera._waitingParentId) {
  25827. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  25828. camera._waitingParentId = undefined;
  25829. }
  25830. }
  25831. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  25832. var light = scene.lights[index];
  25833. if (light._waitingParentId) {
  25834. light.parent = scene.getLastEntryByID(light._waitingParentId);
  25835. light._waitingParentId = undefined;
  25836. }
  25837. }
  25838. // Sounds
  25839. var loadedSounds = [];
  25840. var loadedSound;
  25841. if (BABYLON.AudioEngine && parsedData.sounds) {
  25842. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  25843. var parsedSound = parsedData.sounds[index];
  25844. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25845. if (!parsedSound.url)
  25846. parsedSound.url = parsedSound.name;
  25847. if (!loadedSounds[parsedSound.url]) {
  25848. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  25849. loadedSounds[parsedSound.url] = loadedSound;
  25850. }
  25851. else {
  25852. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  25853. }
  25854. }
  25855. else {
  25856. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  25857. }
  25858. }
  25859. }
  25860. loadedSounds = [];
  25861. // Connect parents & children and parse actions
  25862. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25863. var mesh = scene.meshes[index];
  25864. if (mesh._waitingParentId) {
  25865. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  25866. mesh._waitingParentId = undefined;
  25867. }
  25868. if (mesh._waitingActions) {
  25869. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  25870. mesh._waitingActions = undefined;
  25871. }
  25872. }
  25873. // freeze world matrix application
  25874. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  25875. var currentMesh = scene.meshes[index];
  25876. if (currentMesh._waitingFreezeWorldMatrix) {
  25877. currentMesh.freezeWorldMatrix();
  25878. currentMesh._waitingFreezeWorldMatrix = undefined;
  25879. }
  25880. else {
  25881. currentMesh.computeWorldMatrix(true);
  25882. }
  25883. }
  25884. // Particles Systems
  25885. if (parsedData.particleSystems) {
  25886. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  25887. var parsedParticleSystem = parsedData.particleSystems[index];
  25888. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  25889. }
  25890. }
  25891. // Lens flares
  25892. if (parsedData.lensFlareSystems) {
  25893. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  25894. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  25895. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  25896. }
  25897. }
  25898. // Shadows
  25899. if (parsedData.shadowGenerators) {
  25900. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  25901. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  25902. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  25903. }
  25904. }
  25905. // Actions (scene)
  25906. if (parsedData.actions) {
  25907. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  25908. }
  25909. // Finish
  25910. return true;
  25911. }
  25912. catch (err) {
  25913. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  25914. log = null;
  25915. throw err;
  25916. }
  25917. finally {
  25918. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  25919. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  25920. }
  25921. }
  25922. }
  25923. });
  25924. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25925. })(BABYLON || (BABYLON = {}));
  25926. var BABYLON;
  25927. (function (BABYLON) {
  25928. var SpriteManager = (function () {
  25929. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  25930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25931. this.name = name;
  25932. this.sprites = new Array();
  25933. this.renderingGroupId = 0;
  25934. this.layerMask = 0x0FFFFFFF;
  25935. this.fogEnabled = true;
  25936. this.isPickable = false;
  25937. /**
  25938. * An event triggered when the manager is disposed.
  25939. * @type {BABYLON.Observable}
  25940. */
  25941. this.onDisposeObservable = new BABYLON.Observable();
  25942. this._vertexBuffers = {};
  25943. this._capacity = capacity;
  25944. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  25945. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25946. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25947. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  25948. if (cellSize.width) {
  25949. this.cellWidth = cellSize.width;
  25950. this.cellHeight = cellSize.height;
  25951. }
  25952. else {
  25953. this.cellWidth = cellSize;
  25954. this.cellHeight = cellSize;
  25955. }
  25956. this._scene = scene;
  25957. this._scene.spriteManagers.push(this);
  25958. var indices = [];
  25959. var index = 0;
  25960. for (var count = 0; count < capacity; count++) {
  25961. indices.push(index);
  25962. indices.push(index + 1);
  25963. indices.push(index + 2);
  25964. indices.push(index);
  25965. indices.push(index + 2);
  25966. indices.push(index + 3);
  25967. index += 4;
  25968. }
  25969. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  25970. // VBO
  25971. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  25972. this._vertexData = new Float32Array(capacity * 16 * 4);
  25973. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  25974. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  25975. var options = this._buffer.createVertexBuffer("options", 4, 4);
  25976. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  25977. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  25978. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  25979. this._vertexBuffers["options"] = options;
  25980. this._vertexBuffers["cellInfo"] = cellInfo;
  25981. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  25982. // Effects
  25983. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  25984. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  25985. }
  25986. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  25987. set: function (callback) {
  25988. if (this._onDisposeObserver) {
  25989. this.onDisposeObservable.remove(this._onDisposeObserver);
  25990. }
  25991. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25992. },
  25993. enumerable: true,
  25994. configurable: true
  25995. });
  25996. Object.defineProperty(SpriteManager.prototype, "texture", {
  25997. get: function () {
  25998. return this._spriteTexture;
  25999. },
  26000. set: function (value) {
  26001. this._spriteTexture = value;
  26002. },
  26003. enumerable: true,
  26004. configurable: true
  26005. });
  26006. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26007. var arrayOffset = index * 16;
  26008. if (offsetX === 0)
  26009. offsetX = this._epsilon;
  26010. else if (offsetX === 1)
  26011. offsetX = 1 - this._epsilon;
  26012. if (offsetY === 0)
  26013. offsetY = this._epsilon;
  26014. else if (offsetY === 1)
  26015. offsetY = 1 - this._epsilon;
  26016. this._vertexData[arrayOffset] = sprite.position.x;
  26017. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26018. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26019. this._vertexData[arrayOffset + 3] = sprite.angle;
  26020. this._vertexData[arrayOffset + 4] = sprite.width;
  26021. this._vertexData[arrayOffset + 5] = sprite.height;
  26022. this._vertexData[arrayOffset + 6] = offsetX;
  26023. this._vertexData[arrayOffset + 7] = offsetY;
  26024. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26025. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26026. var offset = (sprite.cellIndex / rowSize) >> 0;
  26027. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26028. this._vertexData[arrayOffset + 11] = offset;
  26029. // Color
  26030. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26031. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26032. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26033. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26034. };
  26035. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26036. var count = Math.min(this._capacity, this.sprites.length);
  26037. var min = BABYLON.Vector3.Zero();
  26038. var max = BABYLON.Vector3.Zero();
  26039. var distance = Number.MAX_VALUE;
  26040. var currentSprite;
  26041. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26042. var cameraView = camera.getViewMatrix();
  26043. for (var index = 0; index < count; index++) {
  26044. var sprite = this.sprites[index];
  26045. if (!sprite) {
  26046. continue;
  26047. }
  26048. if (predicate) {
  26049. if (!predicate(sprite)) {
  26050. continue;
  26051. }
  26052. }
  26053. else if (!sprite.isPickable) {
  26054. continue;
  26055. }
  26056. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26057. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26058. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26059. if (ray.intersectsBoxMinMax(min, max)) {
  26060. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26061. if (distance > currentDistance) {
  26062. distance = currentDistance;
  26063. currentSprite = sprite;
  26064. if (fastCheck) {
  26065. break;
  26066. }
  26067. }
  26068. }
  26069. }
  26070. if (currentSprite) {
  26071. var result = new BABYLON.PickingInfo();
  26072. result.hit = true;
  26073. result.pickedSprite = currentSprite;
  26074. result.distance = distance;
  26075. return result;
  26076. }
  26077. return null;
  26078. };
  26079. SpriteManager.prototype.render = function () {
  26080. // Check
  26081. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26082. return;
  26083. var engine = this._scene.getEngine();
  26084. var baseSize = this._spriteTexture.getBaseSize();
  26085. // Sprites
  26086. var deltaTime = engine.getDeltaTime();
  26087. var max = Math.min(this._capacity, this.sprites.length);
  26088. var rowSize = baseSize.width / this.cellWidth;
  26089. var offset = 0;
  26090. for (var index = 0; index < max; index++) {
  26091. var sprite = this.sprites[index];
  26092. if (!sprite) {
  26093. continue;
  26094. }
  26095. sprite._animate(deltaTime);
  26096. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26097. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26098. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26099. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26100. }
  26101. this._buffer.update(this._vertexData);
  26102. // Render
  26103. var effect = this._effectBase;
  26104. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26105. effect = this._effectFog;
  26106. }
  26107. engine.enableEffect(effect);
  26108. var viewMatrix = this._scene.getViewMatrix();
  26109. effect.setTexture("diffuseSampler", this._spriteTexture);
  26110. effect.setMatrix("view", viewMatrix);
  26111. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26112. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26113. // Fog
  26114. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26115. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26116. effect.setColor3("vFogColor", this._scene.fogColor);
  26117. }
  26118. // VBOs
  26119. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26120. // Draw order
  26121. engine.setDepthFunctionToLessOrEqual();
  26122. effect.setBool("alphaTest", true);
  26123. engine.setColorWrite(false);
  26124. engine.draw(true, 0, max * 6);
  26125. engine.setColorWrite(true);
  26126. effect.setBool("alphaTest", false);
  26127. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26128. engine.draw(true, 0, max * 6);
  26129. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26130. };
  26131. SpriteManager.prototype.dispose = function () {
  26132. if (this._buffer) {
  26133. this._buffer.dispose();
  26134. this._buffer = null;
  26135. }
  26136. if (this._indexBuffer) {
  26137. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26138. this._indexBuffer = null;
  26139. }
  26140. if (this._spriteTexture) {
  26141. this._spriteTexture.dispose();
  26142. this._spriteTexture = null;
  26143. }
  26144. // Remove from scene
  26145. var index = this._scene.spriteManagers.indexOf(this);
  26146. this._scene.spriteManagers.splice(index, 1);
  26147. // Callback
  26148. this.onDisposeObservable.notifyObservers(this);
  26149. this.onDisposeObservable.clear();
  26150. };
  26151. return SpriteManager;
  26152. })();
  26153. BABYLON.SpriteManager = SpriteManager;
  26154. })(BABYLON || (BABYLON = {}));
  26155. var BABYLON;
  26156. (function (BABYLON) {
  26157. var Sprite = (function () {
  26158. function Sprite(name, manager) {
  26159. this.name = name;
  26160. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26161. this.width = 1.0;
  26162. this.height = 1.0;
  26163. this.angle = 0;
  26164. this.cellIndex = 0;
  26165. this.invertU = 0;
  26166. this.invertV = 0;
  26167. this.animations = new Array();
  26168. this.isPickable = false;
  26169. this._animationStarted = false;
  26170. this._loopAnimation = false;
  26171. this._fromIndex = 0;
  26172. this._toIndex = 0;
  26173. this._delay = 0;
  26174. this._direction = 1;
  26175. this._frameCount = 0;
  26176. this._time = 0;
  26177. this._manager = manager;
  26178. this._manager.sprites.push(this);
  26179. this.position = BABYLON.Vector3.Zero();
  26180. }
  26181. Object.defineProperty(Sprite.prototype, "size", {
  26182. get: function () {
  26183. return this.width;
  26184. },
  26185. set: function (value) {
  26186. this.width = value;
  26187. this.height = value;
  26188. },
  26189. enumerable: true,
  26190. configurable: true
  26191. });
  26192. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  26193. this._fromIndex = from;
  26194. this._toIndex = to;
  26195. this._loopAnimation = loop;
  26196. this._delay = delay;
  26197. this._animationStarted = true;
  26198. this._direction = from < to ? 1 : -1;
  26199. this.cellIndex = from;
  26200. this._time = 0;
  26201. };
  26202. Sprite.prototype.stopAnimation = function () {
  26203. this._animationStarted = false;
  26204. };
  26205. Sprite.prototype._animate = function (deltaTime) {
  26206. if (!this._animationStarted)
  26207. return;
  26208. this._time += deltaTime;
  26209. if (this._time > this._delay) {
  26210. this._time = this._time % this._delay;
  26211. this.cellIndex += this._direction;
  26212. if (this.cellIndex == this._toIndex) {
  26213. if (this._loopAnimation) {
  26214. this.cellIndex = this._fromIndex;
  26215. }
  26216. else {
  26217. this._animationStarted = false;
  26218. if (this.disposeWhenFinishedAnimating) {
  26219. this.dispose();
  26220. }
  26221. }
  26222. }
  26223. }
  26224. };
  26225. Sprite.prototype.dispose = function () {
  26226. for (var i = 0; i < this._manager.sprites.length; i++) {
  26227. if (this._manager.sprites[i] == this) {
  26228. this._manager.sprites.splice(i, 1);
  26229. }
  26230. }
  26231. };
  26232. return Sprite;
  26233. })();
  26234. BABYLON.Sprite = Sprite;
  26235. })(BABYLON || (BABYLON = {}));
  26236. var BABYLON;
  26237. (function (BABYLON) {
  26238. var Layer = (function () {
  26239. function Layer(name, imgUrl, scene, isBackground, color) {
  26240. this.name = name;
  26241. this.scale = new BABYLON.Vector2(1, 1);
  26242. this.offset = new BABYLON.Vector2(0, 0);
  26243. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26244. this._vertexBuffers = {};
  26245. // Events
  26246. /**
  26247. * An event triggered when the layer is disposed.
  26248. * @type {BABYLON.Observable}
  26249. */
  26250. this.onDisposeObservable = new BABYLON.Observable();
  26251. /**
  26252. * An event triggered before rendering the scene
  26253. * @type {BABYLON.Observable}
  26254. */
  26255. this.onBeforeRenderObservable = new BABYLON.Observable();
  26256. /**
  26257. * An event triggered after rendering the scene
  26258. * @type {BABYLON.Observable}
  26259. */
  26260. this.onAfterRenderObservable = new BABYLON.Observable();
  26261. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26262. this.isBackground = isBackground === undefined ? true : isBackground;
  26263. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26264. this._scene = scene;
  26265. this._scene.layers.push(this);
  26266. var engine = scene.getEngine();
  26267. // VBO
  26268. var vertices = [];
  26269. vertices.push(1, 1);
  26270. vertices.push(-1, 1);
  26271. vertices.push(-1, -1);
  26272. vertices.push(1, -1);
  26273. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26274. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26275. // Indices
  26276. var indices = [];
  26277. indices.push(0);
  26278. indices.push(1);
  26279. indices.push(2);
  26280. indices.push(0);
  26281. indices.push(2);
  26282. indices.push(3);
  26283. this._indexBuffer = engine.createIndexBuffer(indices);
  26284. // Effects
  26285. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26286. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26287. }
  26288. Object.defineProperty(Layer.prototype, "onDispose", {
  26289. set: function (callback) {
  26290. if (this._onDisposeObserver) {
  26291. this.onDisposeObservable.remove(this._onDisposeObserver);
  26292. }
  26293. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26294. },
  26295. enumerable: true,
  26296. configurable: true
  26297. });
  26298. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26299. set: function (callback) {
  26300. if (this._onBeforeRenderObserver) {
  26301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26302. }
  26303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26304. },
  26305. enumerable: true,
  26306. configurable: true
  26307. });
  26308. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26309. set: function (callback) {
  26310. if (this._onAfterRenderObserver) {
  26311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26312. }
  26313. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26314. },
  26315. enumerable: true,
  26316. configurable: true
  26317. });
  26318. Layer.prototype.render = function () {
  26319. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26320. // Check
  26321. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26322. return;
  26323. var engine = this._scene.getEngine();
  26324. this.onBeforeRenderObservable.notifyObservers(this);
  26325. // Render
  26326. engine.enableEffect(currentEffect);
  26327. engine.setState(false);
  26328. // Texture
  26329. currentEffect.setTexture("textureSampler", this.texture);
  26330. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26331. // Color
  26332. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26333. // Scale / offset
  26334. currentEffect.setVector2("offset", this.offset);
  26335. currentEffect.setVector2("scale", this.scale);
  26336. // VBOs
  26337. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26338. // Draw order
  26339. if (!this._alphaTestEffect) {
  26340. engine.setAlphaMode(this.alphaBlendingMode);
  26341. engine.draw(true, 0, 6);
  26342. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26343. }
  26344. else {
  26345. engine.draw(true, 0, 6);
  26346. }
  26347. this.onAfterRenderObservable.notifyObservers(this);
  26348. };
  26349. Layer.prototype.dispose = function () {
  26350. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26351. if (vertexBuffer) {
  26352. vertexBuffer.dispose();
  26353. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26354. }
  26355. if (this._indexBuffer) {
  26356. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26357. this._indexBuffer = null;
  26358. }
  26359. if (this.texture) {
  26360. this.texture.dispose();
  26361. this.texture = null;
  26362. }
  26363. // Remove from scene
  26364. var index = this._scene.layers.indexOf(this);
  26365. this._scene.layers.splice(index, 1);
  26366. // Callback
  26367. this.onDisposeObservable.notifyObservers(this);
  26368. this.onDisposeObservable.clear();
  26369. this.onAfterRenderObservable.clear();
  26370. this.onBeforeRenderObservable.clear();
  26371. };
  26372. return Layer;
  26373. })();
  26374. BABYLON.Layer = Layer;
  26375. })(BABYLON || (BABYLON = {}));
  26376. var BABYLON;
  26377. (function (BABYLON) {
  26378. var Particle = (function () {
  26379. function Particle() {
  26380. this.position = BABYLON.Vector3.Zero();
  26381. this.direction = BABYLON.Vector3.Zero();
  26382. this.color = new BABYLON.Color4(0, 0, 0, 0);
  26383. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  26384. this.lifeTime = 1.0;
  26385. this.age = 0;
  26386. this.size = 0;
  26387. this.angle = 0;
  26388. this.angularSpeed = 0;
  26389. }
  26390. Particle.prototype.copyTo = function (other) {
  26391. other.position.copyFrom(this.position);
  26392. other.direction.copyFrom(this.direction);
  26393. other.color.copyFrom(this.color);
  26394. other.colorStep.copyFrom(this.colorStep);
  26395. other.lifeTime = this.lifeTime;
  26396. other.age = this.age;
  26397. other.size = this.size;
  26398. other.angle = this.angle;
  26399. other.angularSpeed = this.angularSpeed;
  26400. };
  26401. return Particle;
  26402. })();
  26403. BABYLON.Particle = Particle;
  26404. })(BABYLON || (BABYLON = {}));
  26405. var BABYLON;
  26406. (function (BABYLON) {
  26407. var randomNumber = function (min, max) {
  26408. if (min === max) {
  26409. return (min);
  26410. }
  26411. var random = Math.random();
  26412. return ((random * (max - min)) + min);
  26413. };
  26414. var ParticleSystem = (function () {
  26415. function ParticleSystem(name, capacity, scene, customEffect) {
  26416. var _this = this;
  26417. this.name = name;
  26418. // Members
  26419. this.animations = [];
  26420. this.renderingGroupId = 0;
  26421. this.emitter = null;
  26422. this.emitRate = 10;
  26423. this.manualEmitCount = -1;
  26424. this.updateSpeed = 0.01;
  26425. this.targetStopDuration = 0;
  26426. this.disposeOnStop = false;
  26427. this.minEmitPower = 1;
  26428. this.maxEmitPower = 1;
  26429. this.minLifeTime = 1;
  26430. this.maxLifeTime = 1;
  26431. this.minSize = 1;
  26432. this.maxSize = 1;
  26433. this.minAngularSpeed = 0;
  26434. this.maxAngularSpeed = 0;
  26435. this.layerMask = 0x0FFFFFFF;
  26436. /**
  26437. * An event triggered when the system is disposed.
  26438. * @type {BABYLON.Observable}
  26439. */
  26440. this.onDisposeObservable = new BABYLON.Observable();
  26441. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  26442. this.forceDepthWrite = false;
  26443. this.gravity = BABYLON.Vector3.Zero();
  26444. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  26445. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  26446. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  26447. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  26448. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26449. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26450. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  26451. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26452. this.particles = new Array();
  26453. this._stockParticles = new Array();
  26454. this._newPartsExcess = 0;
  26455. this._vertexBuffers = {};
  26456. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  26457. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  26458. this._scaledDirection = BABYLON.Vector3.Zero();
  26459. this._scaledGravity = BABYLON.Vector3.Zero();
  26460. this._currentRenderId = -1;
  26461. this._started = false;
  26462. this._stopped = false;
  26463. this._actualFrame = 0;
  26464. this.id = name;
  26465. this._capacity = capacity;
  26466. this._scene = scene;
  26467. this._customEffect = customEffect;
  26468. scene.particleSystems.push(this);
  26469. var indices = [];
  26470. var index = 0;
  26471. for (var count = 0; count < capacity; count++) {
  26472. indices.push(index);
  26473. indices.push(index + 1);
  26474. indices.push(index + 2);
  26475. indices.push(index);
  26476. indices.push(index + 2);
  26477. indices.push(index + 3);
  26478. index += 4;
  26479. }
  26480. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26481. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  26482. this._vertexData = new Float32Array(capacity * 11 * 4);
  26483. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  26484. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  26485. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  26486. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  26487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26488. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26489. this._vertexBuffers["options"] = options;
  26490. // Default behaviors
  26491. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  26492. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  26493. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  26494. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  26495. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  26496. };
  26497. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  26498. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  26499. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  26500. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  26501. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  26502. };
  26503. this.updateFunction = function (particles) {
  26504. for (var index = 0; index < particles.length; index++) {
  26505. var particle = particles[index];
  26506. particle.age += _this._scaledUpdateSpeed;
  26507. if (particle.age >= particle.lifeTime) {
  26508. _this.recycleParticle(particle);
  26509. index--;
  26510. continue;
  26511. }
  26512. else {
  26513. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  26514. particle.color.addInPlace(_this._scaledColorStep);
  26515. if (particle.color.a < 0)
  26516. particle.color.a = 0;
  26517. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  26518. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  26519. particle.position.addInPlace(_this._scaledDirection);
  26520. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  26521. particle.direction.addInPlace(_this._scaledGravity);
  26522. }
  26523. }
  26524. };
  26525. }
  26526. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  26527. set: function (callback) {
  26528. if (this._onDisposeObserver) {
  26529. this.onDisposeObservable.remove(this._onDisposeObserver);
  26530. }
  26531. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26532. },
  26533. enumerable: true,
  26534. configurable: true
  26535. });
  26536. ParticleSystem.prototype.recycleParticle = function (particle) {
  26537. var lastParticle = this.particles.pop();
  26538. if (lastParticle !== particle) {
  26539. lastParticle.copyTo(particle);
  26540. this._stockParticles.push(lastParticle);
  26541. }
  26542. };
  26543. ParticleSystem.prototype.getCapacity = function () {
  26544. return this._capacity;
  26545. };
  26546. ParticleSystem.prototype.isAlive = function () {
  26547. return this._alive;
  26548. };
  26549. ParticleSystem.prototype.isStarted = function () {
  26550. return this._started;
  26551. };
  26552. ParticleSystem.prototype.start = function () {
  26553. this._started = true;
  26554. this._stopped = false;
  26555. this._actualFrame = 0;
  26556. };
  26557. ParticleSystem.prototype.stop = function () {
  26558. this._stopped = true;
  26559. };
  26560. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  26561. var offset = index * 11;
  26562. this._vertexData[offset] = particle.position.x;
  26563. this._vertexData[offset + 1] = particle.position.y;
  26564. this._vertexData[offset + 2] = particle.position.z;
  26565. this._vertexData[offset + 3] = particle.color.r;
  26566. this._vertexData[offset + 4] = particle.color.g;
  26567. this._vertexData[offset + 5] = particle.color.b;
  26568. this._vertexData[offset + 6] = particle.color.a;
  26569. this._vertexData[offset + 7] = particle.angle;
  26570. this._vertexData[offset + 8] = particle.size;
  26571. this._vertexData[offset + 9] = offsetX;
  26572. this._vertexData[offset + 10] = offsetY;
  26573. };
  26574. ParticleSystem.prototype._update = function (newParticles) {
  26575. // Update current
  26576. this._alive = this.particles.length > 0;
  26577. this.updateFunction(this.particles);
  26578. // Add new ones
  26579. var worldMatrix;
  26580. if (this.emitter.position) {
  26581. worldMatrix = this.emitter.getWorldMatrix();
  26582. }
  26583. else {
  26584. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  26585. }
  26586. var particle;
  26587. for (var index = 0; index < newParticles; index++) {
  26588. if (this.particles.length === this._capacity) {
  26589. break;
  26590. }
  26591. if (this._stockParticles.length !== 0) {
  26592. particle = this._stockParticles.pop();
  26593. particle.age = 0;
  26594. }
  26595. else {
  26596. particle = new BABYLON.Particle();
  26597. }
  26598. this.particles.push(particle);
  26599. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  26600. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  26601. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  26602. particle.size = randomNumber(this.minSize, this.maxSize);
  26603. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  26604. this.startPositionFunction(worldMatrix, particle.position, particle);
  26605. var step = randomNumber(0, 1.0);
  26606. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  26607. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  26608. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  26609. }
  26610. };
  26611. ParticleSystem.prototype._getEffect = function () {
  26612. if (this._customEffect) {
  26613. return this._customEffect;
  26614. }
  26615. ;
  26616. var defines = [];
  26617. if (this._scene.clipPlane) {
  26618. defines.push("#define CLIPPLANE");
  26619. }
  26620. // Effect
  26621. var join = defines.join("\n");
  26622. if (this._cachedDefines !== join) {
  26623. this._cachedDefines = join;
  26624. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  26625. }
  26626. return this._effect;
  26627. };
  26628. ParticleSystem.prototype.animate = function () {
  26629. if (!this._started)
  26630. return;
  26631. var effect = this._getEffect();
  26632. // Check
  26633. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  26634. return;
  26635. if (this._currentRenderId === this._scene.getRenderId()) {
  26636. return;
  26637. }
  26638. this._currentRenderId = this._scene.getRenderId();
  26639. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  26640. // determine the number of particles we need to create
  26641. var newParticles;
  26642. if (this.manualEmitCount > -1) {
  26643. newParticles = this.manualEmitCount;
  26644. this._newPartsExcess = 0;
  26645. this.manualEmitCount = 0;
  26646. }
  26647. else {
  26648. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  26649. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  26650. }
  26651. if (this._newPartsExcess > 1.0) {
  26652. newParticles += this._newPartsExcess >> 0;
  26653. this._newPartsExcess -= this._newPartsExcess >> 0;
  26654. }
  26655. this._alive = false;
  26656. if (!this._stopped) {
  26657. this._actualFrame += this._scaledUpdateSpeed;
  26658. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  26659. this.stop();
  26660. }
  26661. else {
  26662. newParticles = 0;
  26663. }
  26664. this._update(newParticles);
  26665. // Stopped?
  26666. if (this._stopped) {
  26667. if (!this._alive) {
  26668. this._started = false;
  26669. if (this.disposeOnStop) {
  26670. this._scene._toBeDisposed.push(this);
  26671. }
  26672. }
  26673. }
  26674. // Update VBO
  26675. var offset = 0;
  26676. for (var index = 0; index < this.particles.length; index++) {
  26677. var particle = this.particles[index];
  26678. this._appendParticleVertex(offset++, particle, 0, 0);
  26679. this._appendParticleVertex(offset++, particle, 1, 0);
  26680. this._appendParticleVertex(offset++, particle, 1, 1);
  26681. this._appendParticleVertex(offset++, particle, 0, 1);
  26682. }
  26683. this._vertexBuffer.update(this._vertexData);
  26684. };
  26685. ParticleSystem.prototype.render = function () {
  26686. var effect = this._getEffect();
  26687. // Check
  26688. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  26689. return 0;
  26690. var engine = this._scene.getEngine();
  26691. // Render
  26692. engine.enableEffect(effect);
  26693. engine.setState(false);
  26694. var viewMatrix = this._scene.getViewMatrix();
  26695. effect.setTexture("diffuseSampler", this.particleTexture);
  26696. effect.setMatrix("view", viewMatrix);
  26697. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26698. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  26699. if (this._scene.clipPlane) {
  26700. var clipPlane = this._scene.clipPlane;
  26701. var invView = viewMatrix.clone();
  26702. invView.invert();
  26703. effect.setMatrix("invView", invView);
  26704. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26705. }
  26706. // VBOs
  26707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26708. // Draw order
  26709. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  26710. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  26711. }
  26712. else {
  26713. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26714. }
  26715. if (this.forceDepthWrite) {
  26716. engine.setDepthWrite(true);
  26717. }
  26718. engine.draw(true, 0, this.particles.length * 6);
  26719. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26720. return this.particles.length;
  26721. };
  26722. ParticleSystem.prototype.dispose = function () {
  26723. if (this._vertexBuffer) {
  26724. this._vertexBuffer.dispose();
  26725. this._vertexBuffer = null;
  26726. }
  26727. if (this._indexBuffer) {
  26728. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26729. this._indexBuffer = null;
  26730. }
  26731. if (this.particleTexture) {
  26732. this.particleTexture.dispose();
  26733. this.particleTexture = null;
  26734. }
  26735. // Remove from scene
  26736. var index = this._scene.particleSystems.indexOf(this);
  26737. this._scene.particleSystems.splice(index, 1);
  26738. // Callback
  26739. this.onDisposeObservable.notifyObservers(this);
  26740. this.onDisposeObservable.clear();
  26741. };
  26742. // Clone
  26743. ParticleSystem.prototype.clone = function (name, newEmitter) {
  26744. var result = new ParticleSystem(name, this._capacity, this._scene);
  26745. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  26746. if (newEmitter === undefined) {
  26747. newEmitter = this.emitter;
  26748. }
  26749. result.emitter = newEmitter;
  26750. if (this.particleTexture) {
  26751. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  26752. }
  26753. result.start();
  26754. return result;
  26755. };
  26756. ParticleSystem.prototype.serialize = function () {
  26757. var serializationObject = {};
  26758. serializationObject.name = this.name;
  26759. serializationObject.id = this.id;
  26760. // Emitter
  26761. if (this.emitter.position) {
  26762. serializationObject.emitterId = this.emitter.id;
  26763. }
  26764. else {
  26765. serializationObject.emitter = this.emitter.asArray();
  26766. }
  26767. serializationObject.capacity = this.getCapacity();
  26768. if (this.particleTexture) {
  26769. serializationObject.textureName = this.particleTexture.name;
  26770. }
  26771. // Animations
  26772. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26773. // Particle system
  26774. serializationObject.minAngularSpeed = this.minAngularSpeed;
  26775. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  26776. serializationObject.minSize = this.minSize;
  26777. serializationObject.maxSize = this.maxSize;
  26778. serializationObject.minEmitPower = this.minEmitPower;
  26779. serializationObject.maxEmitPower = this.maxEmitPower;
  26780. serializationObject.minLifeTime = this.minLifeTime;
  26781. serializationObject.maxLifeTime = this.maxLifeTime;
  26782. serializationObject.emitRate = this.emitRate;
  26783. serializationObject.minEmitBox = this.minEmitBox.asArray();
  26784. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  26785. serializationObject.gravity = this.gravity.asArray();
  26786. serializationObject.direction1 = this.direction1.asArray();
  26787. serializationObject.direction2 = this.direction2.asArray();
  26788. serializationObject.color1 = this.color1.asArray();
  26789. serializationObject.color2 = this.color2.asArray();
  26790. serializationObject.colorDead = this.colorDead.asArray();
  26791. serializationObject.updateSpeed = this.updateSpeed;
  26792. serializationObject.targetStopDuration = this.targetStopDuration;
  26793. serializationObject.textureMask = this.textureMask.asArray();
  26794. serializationObject.blendMode = this.blendMode;
  26795. return serializationObject;
  26796. };
  26797. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  26798. var name = parsedParticleSystem.name;
  26799. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  26800. if (parsedParticleSystem.id) {
  26801. particleSystem.id = parsedParticleSystem.id;
  26802. }
  26803. // Texture
  26804. if (parsedParticleSystem.textureName) {
  26805. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  26806. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  26807. }
  26808. // Emitter
  26809. if (parsedParticleSystem.emitterId) {
  26810. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  26811. }
  26812. else {
  26813. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  26814. }
  26815. // Animations
  26816. if (parsedParticleSystem.animations) {
  26817. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  26818. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  26819. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26820. }
  26821. }
  26822. if (parsedParticleSystem.autoAnimate) {
  26823. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  26824. }
  26825. // Particle system
  26826. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  26827. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  26828. particleSystem.minSize = parsedParticleSystem.minSize;
  26829. particleSystem.maxSize = parsedParticleSystem.maxSize;
  26830. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  26831. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  26832. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  26833. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  26834. particleSystem.emitRate = parsedParticleSystem.emitRate;
  26835. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  26836. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  26837. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  26838. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  26839. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  26840. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  26841. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  26842. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  26843. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  26844. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  26845. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  26846. particleSystem.blendMode = parsedParticleSystem.blendMode;
  26847. if (!parsedParticleSystem.preventAutoStart) {
  26848. particleSystem.start();
  26849. }
  26850. return particleSystem;
  26851. };
  26852. // Statics
  26853. ParticleSystem.BLENDMODE_ONEONE = 0;
  26854. ParticleSystem.BLENDMODE_STANDARD = 1;
  26855. return ParticleSystem;
  26856. })();
  26857. BABYLON.ParticleSystem = ParticleSystem;
  26858. })(BABYLON || (BABYLON = {}));
  26859. var BABYLON;
  26860. (function (BABYLON) {
  26861. var AnimationRange = (function () {
  26862. function AnimationRange(name, from, to) {
  26863. this.name = name;
  26864. this.from = from;
  26865. this.to = to;
  26866. }
  26867. AnimationRange.prototype.clone = function () {
  26868. return new AnimationRange(this.name, this.from, this.to);
  26869. };
  26870. return AnimationRange;
  26871. })();
  26872. BABYLON.AnimationRange = AnimationRange;
  26873. /**
  26874. * Composed of a frame, and an action function
  26875. */
  26876. var AnimationEvent = (function () {
  26877. function AnimationEvent(frame, action, onlyOnce) {
  26878. this.frame = frame;
  26879. this.action = action;
  26880. this.onlyOnce = onlyOnce;
  26881. this.isDone = false;
  26882. }
  26883. return AnimationEvent;
  26884. })();
  26885. BABYLON.AnimationEvent = AnimationEvent;
  26886. var PathCursor = (function () {
  26887. function PathCursor(path) {
  26888. this.path = path;
  26889. this._onchange = new Array();
  26890. this.value = 0;
  26891. this.animations = new Array();
  26892. }
  26893. PathCursor.prototype.getPoint = function () {
  26894. var point = this.path.getPointAtLengthPosition(this.value);
  26895. return new BABYLON.Vector3(point.x, 0, point.y);
  26896. };
  26897. PathCursor.prototype.moveAhead = function (step) {
  26898. if (step === void 0) { step = 0.002; }
  26899. this.move(step);
  26900. return this;
  26901. };
  26902. PathCursor.prototype.moveBack = function (step) {
  26903. if (step === void 0) { step = 0.002; }
  26904. this.move(-step);
  26905. return this;
  26906. };
  26907. PathCursor.prototype.move = function (step) {
  26908. if (Math.abs(step) > 1) {
  26909. throw "step size should be less than 1.";
  26910. }
  26911. this.value += step;
  26912. this.ensureLimits();
  26913. this.raiseOnChange();
  26914. return this;
  26915. };
  26916. PathCursor.prototype.ensureLimits = function () {
  26917. while (this.value > 1) {
  26918. this.value -= 1;
  26919. }
  26920. while (this.value < 0) {
  26921. this.value += 1;
  26922. }
  26923. return this;
  26924. };
  26925. // used by animation engine
  26926. PathCursor.prototype.markAsDirty = function (propertyName) {
  26927. this.ensureLimits();
  26928. this.raiseOnChange();
  26929. return this;
  26930. };
  26931. PathCursor.prototype.raiseOnChange = function () {
  26932. var _this = this;
  26933. this._onchange.forEach(function (f) { return f(_this); });
  26934. return this;
  26935. };
  26936. PathCursor.prototype.onchange = function (f) {
  26937. this._onchange.push(f);
  26938. return this;
  26939. };
  26940. return PathCursor;
  26941. })();
  26942. BABYLON.PathCursor = PathCursor;
  26943. var Animation = (function () {
  26944. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  26945. this.name = name;
  26946. this.targetProperty = targetProperty;
  26947. this.framePerSecond = framePerSecond;
  26948. this.dataType = dataType;
  26949. this.loopMode = loopMode;
  26950. this.enableBlending = enableBlending;
  26951. this._offsetsCache = {};
  26952. this._highLimitsCache = {};
  26953. this._stopped = false;
  26954. this._blendingFactor = 0;
  26955. // The set of event that will be linked to this animation
  26956. this._events = new Array();
  26957. this.allowMatricesInterpolation = false;
  26958. this.blendingSpeed = 0.01;
  26959. this._ranges = {};
  26960. this.targetPropertyPath = targetProperty.split(".");
  26961. this.dataType = dataType;
  26962. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  26963. }
  26964. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  26965. var dataType = undefined;
  26966. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  26967. dataType = Animation.ANIMATIONTYPE_FLOAT;
  26968. }
  26969. else if (from instanceof BABYLON.Quaternion) {
  26970. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  26971. }
  26972. else if (from instanceof BABYLON.Vector3) {
  26973. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  26974. }
  26975. else if (from instanceof BABYLON.Vector2) {
  26976. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  26977. }
  26978. else if (from instanceof BABYLON.Color3) {
  26979. dataType = Animation.ANIMATIONTYPE_COLOR3;
  26980. }
  26981. else if (from instanceof BABYLON.Size) {
  26982. dataType = Animation.ANIMATIONTYPE_SIZE;
  26983. }
  26984. if (dataType == undefined) {
  26985. return null;
  26986. }
  26987. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  26988. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  26989. animation.setKeys(keys);
  26990. if (easingFunction !== undefined) {
  26991. animation.setEasingFunction(easingFunction);
  26992. }
  26993. return animation;
  26994. };
  26995. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  26996. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  26997. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  26998. };
  26999. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27000. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27001. node.animations.push(animation);
  27002. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27003. };
  27004. // Methods
  27005. /**
  27006. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27007. */
  27008. Animation.prototype.toString = function (fullDetails) {
  27009. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27010. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27011. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27012. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27013. if (fullDetails) {
  27014. ret += ", Ranges: {";
  27015. var first = true;
  27016. for (var name in this._ranges) {
  27017. if (first) {
  27018. ret += ", ";
  27019. first = false;
  27020. }
  27021. ret += name;
  27022. }
  27023. ret += "}";
  27024. }
  27025. return ret;
  27026. };
  27027. /**
  27028. * Add an event to this animation.
  27029. */
  27030. Animation.prototype.addEvent = function (event) {
  27031. this._events.push(event);
  27032. };
  27033. /**
  27034. * Remove all events found at the given frame
  27035. * @param frame
  27036. */
  27037. Animation.prototype.removeEvents = function (frame) {
  27038. for (var index = 0; index < this._events.length; index++) {
  27039. if (this._events[index].frame === frame) {
  27040. this._events.splice(index, 1);
  27041. index--;
  27042. }
  27043. }
  27044. };
  27045. Animation.prototype.createRange = function (name, from, to) {
  27046. // check name not already in use; could happen for bones after serialized
  27047. if (!this._ranges[name]) {
  27048. this._ranges[name] = new AnimationRange(name, from, to);
  27049. }
  27050. };
  27051. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27052. if (deleteFrames === void 0) { deleteFrames = true; }
  27053. if (this._ranges[name]) {
  27054. if (deleteFrames) {
  27055. var from = this._ranges[name].from;
  27056. var to = this._ranges[name].to;
  27057. // this loop MUST go high to low for multiple splices to work
  27058. for (var key = this._keys.length - 1; key >= 0; key--) {
  27059. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27060. this._keys.splice(key, 1);
  27061. }
  27062. }
  27063. }
  27064. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27065. }
  27066. };
  27067. Animation.prototype.getRange = function (name) {
  27068. return this._ranges[name];
  27069. };
  27070. Animation.prototype.reset = function () {
  27071. this._offsetsCache = {};
  27072. this._highLimitsCache = {};
  27073. this.currentFrame = 0;
  27074. this._blendingFactor = 0;
  27075. this._originalBlendValue = null;
  27076. };
  27077. Animation.prototype.isStopped = function () {
  27078. return this._stopped;
  27079. };
  27080. Animation.prototype.getKeys = function () {
  27081. return this._keys;
  27082. };
  27083. Animation.prototype.getHighestFrame = function () {
  27084. var ret = 0;
  27085. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27086. if (ret < this._keys[key].frame) {
  27087. ret = this._keys[key].frame;
  27088. }
  27089. }
  27090. return ret;
  27091. };
  27092. Animation.prototype.getEasingFunction = function () {
  27093. return this._easingFunction;
  27094. };
  27095. Animation.prototype.setEasingFunction = function (easingFunction) {
  27096. this._easingFunction = easingFunction;
  27097. };
  27098. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27099. return startValue + (endValue - startValue) * gradient;
  27100. };
  27101. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27102. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27103. };
  27104. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27105. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27106. };
  27107. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27108. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27109. };
  27110. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27111. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27112. };
  27113. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27114. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27115. };
  27116. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27117. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27118. };
  27119. Animation.prototype.clone = function () {
  27120. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27121. if (this._keys) {
  27122. clone.setKeys(this._keys);
  27123. }
  27124. if (this._ranges) {
  27125. clone._ranges = {};
  27126. for (var name in this._ranges) {
  27127. clone._ranges[name] = this._ranges[name].clone();
  27128. }
  27129. }
  27130. return clone;
  27131. };
  27132. Animation.prototype.setKeys = function (values) {
  27133. this._keys = values.slice(0);
  27134. this._offsetsCache = {};
  27135. this._highLimitsCache = {};
  27136. };
  27137. Animation.prototype._getKeyValue = function (value) {
  27138. if (typeof value === "function") {
  27139. return value();
  27140. }
  27141. return value;
  27142. };
  27143. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27144. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27145. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27146. }
  27147. this.currentFrame = currentFrame;
  27148. // Try to get a hash to find the right key
  27149. 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));
  27150. if (this._keys[startKey].frame >= currentFrame) {
  27151. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27152. startKey--;
  27153. }
  27154. }
  27155. for (var key = startKey; key < this._keys.length; key++) {
  27156. if (this._keys[key + 1].frame >= currentFrame) {
  27157. var startValue = this._getKeyValue(this._keys[key].value);
  27158. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27159. // gradient : percent of currentFrame between the frame inf and the frame sup
  27160. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27161. // check for easingFunction and correction of gradient
  27162. if (this._easingFunction != null) {
  27163. gradient = this._easingFunction.ease(gradient);
  27164. }
  27165. switch (this.dataType) {
  27166. // Float
  27167. case Animation.ANIMATIONTYPE_FLOAT:
  27168. switch (loopMode) {
  27169. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27170. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27171. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27172. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27173. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27174. }
  27175. break;
  27176. // Quaternion
  27177. case Animation.ANIMATIONTYPE_QUATERNION:
  27178. var quaternion = null;
  27179. switch (loopMode) {
  27180. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27181. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27182. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27183. break;
  27184. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27185. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27186. break;
  27187. }
  27188. return quaternion;
  27189. // Vector3
  27190. case Animation.ANIMATIONTYPE_VECTOR3:
  27191. switch (loopMode) {
  27192. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27193. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27194. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27195. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27196. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27197. }
  27198. // Vector2
  27199. case Animation.ANIMATIONTYPE_VECTOR2:
  27200. switch (loopMode) {
  27201. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27202. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27203. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27204. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27205. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27206. }
  27207. // Size
  27208. case Animation.ANIMATIONTYPE_SIZE:
  27209. switch (loopMode) {
  27210. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27211. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27212. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27213. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27214. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27215. }
  27216. // Color3
  27217. case Animation.ANIMATIONTYPE_COLOR3:
  27218. switch (loopMode) {
  27219. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27220. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27221. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27222. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27223. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27224. }
  27225. // Matrix
  27226. case Animation.ANIMATIONTYPE_MATRIX:
  27227. switch (loopMode) {
  27228. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27229. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27230. if (this.allowMatricesInterpolation) {
  27231. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27232. }
  27233. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27234. return startValue;
  27235. }
  27236. default:
  27237. break;
  27238. }
  27239. break;
  27240. }
  27241. }
  27242. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27243. };
  27244. Animation.prototype.setValue = function (currentValue, blend) {
  27245. if (blend === void 0) { blend = false; }
  27246. // Set value
  27247. var path;
  27248. var destination;
  27249. if (this.targetPropertyPath.length > 1) {
  27250. var property = this._target[this.targetPropertyPath[0]];
  27251. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27252. property = property[this.targetPropertyPath[index]];
  27253. }
  27254. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27255. destination = property;
  27256. }
  27257. else {
  27258. path = this.targetPropertyPath[0];
  27259. destination = this._target;
  27260. }
  27261. // Blending
  27262. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27263. if (!this._originalBlendValue) {
  27264. if (destination[path].clone) {
  27265. this._originalBlendValue = destination[path].clone();
  27266. }
  27267. else {
  27268. this._originalBlendValue = destination[path];
  27269. }
  27270. }
  27271. if (this._originalBlendValue.prototype) {
  27272. if (this._originalBlendValue.prototype.Lerp) {
  27273. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27274. }
  27275. else {
  27276. destination[path] = currentValue;
  27277. }
  27278. }
  27279. else if (this._originalBlendValue.m) {
  27280. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27281. }
  27282. else {
  27283. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27284. }
  27285. this._blendingFactor += this.blendingSpeed;
  27286. }
  27287. else {
  27288. destination[path] = currentValue;
  27289. }
  27290. if (this._target.markAsDirty) {
  27291. this._target.markAsDirty(this.targetProperty);
  27292. }
  27293. };
  27294. Animation.prototype.goToFrame = function (frame) {
  27295. if (frame < this._keys[0].frame) {
  27296. frame = this._keys[0].frame;
  27297. }
  27298. else if (frame > this._keys[this._keys.length - 1].frame) {
  27299. frame = this._keys[this._keys.length - 1].frame;
  27300. }
  27301. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27302. this.setValue(currentValue);
  27303. };
  27304. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27305. if (blend === void 0) { blend = false; }
  27306. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27307. this._stopped = true;
  27308. return false;
  27309. }
  27310. var returnValue = true;
  27311. // Adding a start key at frame 0 if missing
  27312. if (this._keys[0].frame !== 0) {
  27313. var newKey = { frame: 0, value: this._keys[0].value };
  27314. this._keys.splice(0, 0, newKey);
  27315. }
  27316. // Check limits
  27317. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27318. from = this._keys[0].frame;
  27319. }
  27320. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27321. to = this._keys[this._keys.length - 1].frame;
  27322. }
  27323. // Compute ratio
  27324. var range = to - from;
  27325. var offsetValue;
  27326. // ratio represents the frame delta between from and to
  27327. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27328. var highLimitValue = 0;
  27329. if (ratio > range && !loop) {
  27330. returnValue = false;
  27331. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27332. }
  27333. else {
  27334. // Get max value if required
  27335. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27336. var keyOffset = to.toString() + from.toString();
  27337. if (!this._offsetsCache[keyOffset]) {
  27338. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27339. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27340. switch (this.dataType) {
  27341. // Float
  27342. case Animation.ANIMATIONTYPE_FLOAT:
  27343. this._offsetsCache[keyOffset] = toValue - fromValue;
  27344. break;
  27345. // Quaternion
  27346. case Animation.ANIMATIONTYPE_QUATERNION:
  27347. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27348. break;
  27349. // Vector3
  27350. case Animation.ANIMATIONTYPE_VECTOR3:
  27351. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27352. // Vector2
  27353. case Animation.ANIMATIONTYPE_VECTOR2:
  27354. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27355. // Size
  27356. case Animation.ANIMATIONTYPE_SIZE:
  27357. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27358. // Color3
  27359. case Animation.ANIMATIONTYPE_COLOR3:
  27360. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27361. default:
  27362. break;
  27363. }
  27364. this._highLimitsCache[keyOffset] = toValue;
  27365. }
  27366. highLimitValue = this._highLimitsCache[keyOffset];
  27367. offsetValue = this._offsetsCache[keyOffset];
  27368. }
  27369. }
  27370. if (offsetValue === undefined) {
  27371. switch (this.dataType) {
  27372. // Float
  27373. case Animation.ANIMATIONTYPE_FLOAT:
  27374. offsetValue = 0;
  27375. break;
  27376. // Quaternion
  27377. case Animation.ANIMATIONTYPE_QUATERNION:
  27378. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  27379. break;
  27380. // Vector3
  27381. case Animation.ANIMATIONTYPE_VECTOR3:
  27382. offsetValue = BABYLON.Vector3.Zero();
  27383. break;
  27384. // Vector2
  27385. case Animation.ANIMATIONTYPE_VECTOR2:
  27386. offsetValue = BABYLON.Vector2.Zero();
  27387. break;
  27388. // Size
  27389. case Animation.ANIMATIONTYPE_SIZE:
  27390. offsetValue = BABYLON.Size.Zero();
  27391. break;
  27392. // Color3
  27393. case Animation.ANIMATIONTYPE_COLOR3:
  27394. offsetValue = BABYLON.Color3.Black();
  27395. }
  27396. }
  27397. // Compute value
  27398. var repeatCount = (ratio / range) >> 0;
  27399. var currentFrame = returnValue ? from + ratio % range : to;
  27400. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  27401. // Set value
  27402. this.setValue(currentValue);
  27403. // Check events
  27404. for (var index = 0; index < this._events.length; index++) {
  27405. if (currentFrame >= this._events[index].frame) {
  27406. var event = this._events[index];
  27407. if (!event.isDone) {
  27408. // If event should be done only once, remove it.
  27409. if (event.onlyOnce) {
  27410. this._events.splice(index, 1);
  27411. index--;
  27412. }
  27413. event.isDone = true;
  27414. event.action();
  27415. } // Don't do anything if the event has already be done.
  27416. }
  27417. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  27418. // reset event, the animation is looping
  27419. this._events[index].isDone = false;
  27420. }
  27421. }
  27422. if (!returnValue) {
  27423. this._stopped = true;
  27424. }
  27425. return returnValue;
  27426. };
  27427. Animation.prototype.serialize = function () {
  27428. var serializationObject = {};
  27429. serializationObject.name = this.name;
  27430. serializationObject.property = this.targetProperty;
  27431. serializationObject.framePerSecond = this.framePerSecond;
  27432. serializationObject.dataType = this.dataType;
  27433. serializationObject.loopBehavior = this.loopMode;
  27434. var dataType = this.dataType;
  27435. serializationObject.keys = [];
  27436. var keys = this.getKeys();
  27437. for (var index = 0; index < keys.length; index++) {
  27438. var animationKey = keys[index];
  27439. var key = {};
  27440. key.frame = animationKey.frame;
  27441. switch (dataType) {
  27442. case Animation.ANIMATIONTYPE_FLOAT:
  27443. key.values = [animationKey.value];
  27444. break;
  27445. case Animation.ANIMATIONTYPE_QUATERNION:
  27446. case Animation.ANIMATIONTYPE_MATRIX:
  27447. case Animation.ANIMATIONTYPE_VECTOR3:
  27448. case Animation.ANIMATIONTYPE_COLOR3:
  27449. key.values = animationKey.value.asArray();
  27450. break;
  27451. }
  27452. serializationObject.keys.push(key);
  27453. }
  27454. serializationObject.ranges = [];
  27455. for (var name in this._ranges) {
  27456. var range = {};
  27457. range.name = name;
  27458. range.from = this._ranges[name].from;
  27459. range.to = this._ranges[name].to;
  27460. serializationObject.ranges.push(range);
  27461. }
  27462. return serializationObject;
  27463. };
  27464. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  27465. get: function () {
  27466. return Animation._ANIMATIONTYPE_FLOAT;
  27467. },
  27468. enumerable: true,
  27469. configurable: true
  27470. });
  27471. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  27472. get: function () {
  27473. return Animation._ANIMATIONTYPE_VECTOR3;
  27474. },
  27475. enumerable: true,
  27476. configurable: true
  27477. });
  27478. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  27479. get: function () {
  27480. return Animation._ANIMATIONTYPE_VECTOR2;
  27481. },
  27482. enumerable: true,
  27483. configurable: true
  27484. });
  27485. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  27486. get: function () {
  27487. return Animation._ANIMATIONTYPE_SIZE;
  27488. },
  27489. enumerable: true,
  27490. configurable: true
  27491. });
  27492. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  27493. get: function () {
  27494. return Animation._ANIMATIONTYPE_QUATERNION;
  27495. },
  27496. enumerable: true,
  27497. configurable: true
  27498. });
  27499. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  27500. get: function () {
  27501. return Animation._ANIMATIONTYPE_MATRIX;
  27502. },
  27503. enumerable: true,
  27504. configurable: true
  27505. });
  27506. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  27507. get: function () {
  27508. return Animation._ANIMATIONTYPE_COLOR3;
  27509. },
  27510. enumerable: true,
  27511. configurable: true
  27512. });
  27513. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  27514. get: function () {
  27515. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  27516. },
  27517. enumerable: true,
  27518. configurable: true
  27519. });
  27520. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  27521. get: function () {
  27522. return Animation._ANIMATIONLOOPMODE_CYCLE;
  27523. },
  27524. enumerable: true,
  27525. configurable: true
  27526. });
  27527. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  27528. get: function () {
  27529. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  27530. },
  27531. enumerable: true,
  27532. configurable: true
  27533. });
  27534. Animation.Parse = function (parsedAnimation) {
  27535. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  27536. var dataType = parsedAnimation.dataType;
  27537. var keys = [];
  27538. var data;
  27539. var index;
  27540. for (index = 0; index < parsedAnimation.keys.length; index++) {
  27541. var key = parsedAnimation.keys[index];
  27542. switch (dataType) {
  27543. case Animation.ANIMATIONTYPE_FLOAT:
  27544. data = key.values[0];
  27545. break;
  27546. case Animation.ANIMATIONTYPE_QUATERNION:
  27547. data = BABYLON.Quaternion.FromArray(key.values);
  27548. break;
  27549. case Animation.ANIMATIONTYPE_MATRIX:
  27550. data = BABYLON.Matrix.FromArray(key.values);
  27551. break;
  27552. case Animation.ANIMATIONTYPE_COLOR3:
  27553. data = BABYLON.Color3.FromArray(key.values);
  27554. break;
  27555. case Animation.ANIMATIONTYPE_VECTOR3:
  27556. default:
  27557. data = BABYLON.Vector3.FromArray(key.values);
  27558. break;
  27559. }
  27560. keys.push({
  27561. frame: key.frame,
  27562. value: data
  27563. });
  27564. }
  27565. animation.setKeys(keys);
  27566. if (parsedAnimation.ranges) {
  27567. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  27568. data = parsedAnimation.ranges[index];
  27569. animation.createRange(data.name, data.from, data.to);
  27570. }
  27571. }
  27572. return animation;
  27573. };
  27574. Animation.AppendSerializedAnimations = function (source, destination) {
  27575. if (source.animations) {
  27576. destination.animations = [];
  27577. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  27578. var animation = source.animations[animationIndex];
  27579. destination.animations.push(animation.serialize());
  27580. }
  27581. }
  27582. };
  27583. // Statics
  27584. Animation._ANIMATIONTYPE_FLOAT = 0;
  27585. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  27586. Animation._ANIMATIONTYPE_QUATERNION = 2;
  27587. Animation._ANIMATIONTYPE_MATRIX = 3;
  27588. Animation._ANIMATIONTYPE_COLOR3 = 4;
  27589. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  27590. Animation._ANIMATIONTYPE_SIZE = 6;
  27591. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  27592. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  27593. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  27594. return Animation;
  27595. })();
  27596. BABYLON.Animation = Animation;
  27597. })(BABYLON || (BABYLON = {}));
  27598. var BABYLON;
  27599. (function (BABYLON) {
  27600. var Animatable = (function () {
  27601. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  27602. if (fromFrame === void 0) { fromFrame = 0; }
  27603. if (toFrame === void 0) { toFrame = 100; }
  27604. if (loopAnimation === void 0) { loopAnimation = false; }
  27605. if (speedRatio === void 0) { speedRatio = 1.0; }
  27606. this.target = target;
  27607. this.fromFrame = fromFrame;
  27608. this.toFrame = toFrame;
  27609. this.loopAnimation = loopAnimation;
  27610. this.speedRatio = speedRatio;
  27611. this.onAnimationEnd = onAnimationEnd;
  27612. this._animations = new Array();
  27613. this._paused = false;
  27614. this.animationStarted = false;
  27615. if (animations) {
  27616. this.appendAnimations(target, animations);
  27617. }
  27618. this._scene = scene;
  27619. scene._activeAnimatables.push(this);
  27620. }
  27621. // Methods
  27622. Animatable.prototype.getAnimations = function () {
  27623. return this._animations;
  27624. };
  27625. Animatable.prototype.appendAnimations = function (target, animations) {
  27626. for (var index = 0; index < animations.length; index++) {
  27627. var animation = animations[index];
  27628. animation._target = target;
  27629. this._animations.push(animation);
  27630. }
  27631. };
  27632. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  27633. var animations = this._animations;
  27634. for (var index = 0; index < animations.length; index++) {
  27635. if (animations[index].targetProperty === property) {
  27636. return animations[index];
  27637. }
  27638. }
  27639. return null;
  27640. };
  27641. Animatable.prototype.reset = function () {
  27642. var animations = this._animations;
  27643. for (var index = 0; index < animations.length; index++) {
  27644. animations[index].reset();
  27645. }
  27646. this._localDelayOffset = null;
  27647. this._pausedDelay = null;
  27648. };
  27649. Animatable.prototype.enableBlending = function (blendingSpeed) {
  27650. var animations = this._animations;
  27651. for (var index = 0; index < animations.length; index++) {
  27652. animations[index].enableBlending = true;
  27653. animations[index].blendingSpeed = blendingSpeed;
  27654. }
  27655. };
  27656. Animatable.prototype.disableBlending = function () {
  27657. var animations = this._animations;
  27658. for (var index = 0; index < animations.length; index++) {
  27659. animations[index].enableBlending = false;
  27660. }
  27661. };
  27662. Animatable.prototype.goToFrame = function (frame) {
  27663. var animations = this._animations;
  27664. for (var index = 0; index < animations.length; index++) {
  27665. animations[index].goToFrame(frame);
  27666. }
  27667. };
  27668. Animatable.prototype.pause = function () {
  27669. if (this._paused) {
  27670. return;
  27671. }
  27672. this._paused = true;
  27673. };
  27674. Animatable.prototype.restart = function () {
  27675. this._paused = false;
  27676. };
  27677. Animatable.prototype.stop = function () {
  27678. var index = this._scene._activeAnimatables.indexOf(this);
  27679. if (index > -1) {
  27680. this._scene._activeAnimatables.splice(index, 1);
  27681. var animations = this._animations;
  27682. for (var index = 0; index < animations.length; index++) {
  27683. animations[index].reset();
  27684. }
  27685. if (this.onAnimationEnd) {
  27686. this.onAnimationEnd();
  27687. }
  27688. }
  27689. };
  27690. Animatable.prototype._animate = function (delay) {
  27691. if (this._paused) {
  27692. this.animationStarted = false;
  27693. if (!this._pausedDelay) {
  27694. this._pausedDelay = delay;
  27695. }
  27696. return true;
  27697. }
  27698. if (!this._localDelayOffset) {
  27699. this._localDelayOffset = delay;
  27700. }
  27701. else if (this._pausedDelay) {
  27702. this._localDelayOffset += delay - this._pausedDelay;
  27703. this._pausedDelay = null;
  27704. }
  27705. // Animating
  27706. var running = false;
  27707. var animations = this._animations;
  27708. var index;
  27709. for (index = 0; index < animations.length; index++) {
  27710. var animation = animations[index];
  27711. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  27712. running = running || isRunning;
  27713. }
  27714. this.animationStarted = running;
  27715. if (!running) {
  27716. // Remove from active animatables
  27717. index = this._scene._activeAnimatables.indexOf(this);
  27718. this._scene._activeAnimatables.splice(index, 1);
  27719. }
  27720. if (!running && this.onAnimationEnd) {
  27721. this.onAnimationEnd();
  27722. this.onAnimationEnd = null;
  27723. }
  27724. return running;
  27725. };
  27726. return Animatable;
  27727. })();
  27728. BABYLON.Animatable = Animatable;
  27729. })(BABYLON || (BABYLON = {}));
  27730. var BABYLON;
  27731. (function (BABYLON) {
  27732. var EasingFunction = (function () {
  27733. function EasingFunction() {
  27734. // Properties
  27735. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  27736. }
  27737. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  27738. get: function () {
  27739. return EasingFunction._EASINGMODE_EASEIN;
  27740. },
  27741. enumerable: true,
  27742. configurable: true
  27743. });
  27744. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  27745. get: function () {
  27746. return EasingFunction._EASINGMODE_EASEOUT;
  27747. },
  27748. enumerable: true,
  27749. configurable: true
  27750. });
  27751. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  27752. get: function () {
  27753. return EasingFunction._EASINGMODE_EASEINOUT;
  27754. },
  27755. enumerable: true,
  27756. configurable: true
  27757. });
  27758. EasingFunction.prototype.setEasingMode = function (easingMode) {
  27759. var n = Math.min(Math.max(easingMode, 0), 2);
  27760. this._easingMode = n;
  27761. };
  27762. EasingFunction.prototype.getEasingMode = function () {
  27763. return this._easingMode;
  27764. };
  27765. EasingFunction.prototype.easeInCore = function (gradient) {
  27766. throw new Error('You must implement this method');
  27767. };
  27768. EasingFunction.prototype.ease = function (gradient) {
  27769. switch (this._easingMode) {
  27770. case EasingFunction.EASINGMODE_EASEIN:
  27771. return this.easeInCore(gradient);
  27772. case EasingFunction.EASINGMODE_EASEOUT:
  27773. return (1 - this.easeInCore(1 - gradient));
  27774. }
  27775. if (gradient >= 0.5) {
  27776. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  27777. }
  27778. return (this.easeInCore(gradient * 2) * 0.5);
  27779. };
  27780. //Statics
  27781. EasingFunction._EASINGMODE_EASEIN = 0;
  27782. EasingFunction._EASINGMODE_EASEOUT = 1;
  27783. EasingFunction._EASINGMODE_EASEINOUT = 2;
  27784. return EasingFunction;
  27785. })();
  27786. BABYLON.EasingFunction = EasingFunction;
  27787. var CircleEase = (function (_super) {
  27788. __extends(CircleEase, _super);
  27789. function CircleEase() {
  27790. _super.apply(this, arguments);
  27791. }
  27792. CircleEase.prototype.easeInCore = function (gradient) {
  27793. gradient = Math.max(0, Math.min(1, gradient));
  27794. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  27795. };
  27796. return CircleEase;
  27797. })(EasingFunction);
  27798. BABYLON.CircleEase = CircleEase;
  27799. var BackEase = (function (_super) {
  27800. __extends(BackEase, _super);
  27801. function BackEase(amplitude) {
  27802. if (amplitude === void 0) { amplitude = 1; }
  27803. _super.call(this);
  27804. this.amplitude = amplitude;
  27805. }
  27806. BackEase.prototype.easeInCore = function (gradient) {
  27807. var num = Math.max(0, this.amplitude);
  27808. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  27809. };
  27810. return BackEase;
  27811. })(EasingFunction);
  27812. BABYLON.BackEase = BackEase;
  27813. var BounceEase = (function (_super) {
  27814. __extends(BounceEase, _super);
  27815. function BounceEase(bounces, bounciness) {
  27816. if (bounces === void 0) { bounces = 3; }
  27817. if (bounciness === void 0) { bounciness = 2; }
  27818. _super.call(this);
  27819. this.bounces = bounces;
  27820. this.bounciness = bounciness;
  27821. }
  27822. BounceEase.prototype.easeInCore = function (gradient) {
  27823. var y = Math.max(0.0, this.bounces);
  27824. var bounciness = this.bounciness;
  27825. if (bounciness <= 1.0) {
  27826. bounciness = 1.001;
  27827. }
  27828. var num9 = Math.pow(bounciness, y);
  27829. var num5 = 1.0 - bounciness;
  27830. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  27831. var num15 = gradient * num4;
  27832. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  27833. var num3 = Math.floor(num65);
  27834. var num13 = num3 + 1.0;
  27835. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  27836. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  27837. var num7 = (num8 + num12) * 0.5;
  27838. var num6 = gradient - num7;
  27839. var num2 = num7 - num8;
  27840. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  27841. };
  27842. return BounceEase;
  27843. })(EasingFunction);
  27844. BABYLON.BounceEase = BounceEase;
  27845. var CubicEase = (function (_super) {
  27846. __extends(CubicEase, _super);
  27847. function CubicEase() {
  27848. _super.apply(this, arguments);
  27849. }
  27850. CubicEase.prototype.easeInCore = function (gradient) {
  27851. return (gradient * gradient * gradient);
  27852. };
  27853. return CubicEase;
  27854. })(EasingFunction);
  27855. BABYLON.CubicEase = CubicEase;
  27856. var ElasticEase = (function (_super) {
  27857. __extends(ElasticEase, _super);
  27858. function ElasticEase(oscillations, springiness) {
  27859. if (oscillations === void 0) { oscillations = 3; }
  27860. if (springiness === void 0) { springiness = 3; }
  27861. _super.call(this);
  27862. this.oscillations = oscillations;
  27863. this.springiness = springiness;
  27864. }
  27865. ElasticEase.prototype.easeInCore = function (gradient) {
  27866. var num2;
  27867. var num3 = Math.max(0.0, this.oscillations);
  27868. var num = Math.max(0.0, this.springiness);
  27869. if (num == 0) {
  27870. num2 = gradient;
  27871. }
  27872. else {
  27873. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  27874. }
  27875. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  27876. };
  27877. return ElasticEase;
  27878. })(EasingFunction);
  27879. BABYLON.ElasticEase = ElasticEase;
  27880. var ExponentialEase = (function (_super) {
  27881. __extends(ExponentialEase, _super);
  27882. function ExponentialEase(exponent) {
  27883. if (exponent === void 0) { exponent = 2; }
  27884. _super.call(this);
  27885. this.exponent = exponent;
  27886. }
  27887. ExponentialEase.prototype.easeInCore = function (gradient) {
  27888. if (this.exponent <= 0) {
  27889. return gradient;
  27890. }
  27891. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  27892. };
  27893. return ExponentialEase;
  27894. })(EasingFunction);
  27895. BABYLON.ExponentialEase = ExponentialEase;
  27896. var PowerEase = (function (_super) {
  27897. __extends(PowerEase, _super);
  27898. function PowerEase(power) {
  27899. if (power === void 0) { power = 2; }
  27900. _super.call(this);
  27901. this.power = power;
  27902. }
  27903. PowerEase.prototype.easeInCore = function (gradient) {
  27904. var y = Math.max(0.0, this.power);
  27905. return Math.pow(gradient, y);
  27906. };
  27907. return PowerEase;
  27908. })(EasingFunction);
  27909. BABYLON.PowerEase = PowerEase;
  27910. var QuadraticEase = (function (_super) {
  27911. __extends(QuadraticEase, _super);
  27912. function QuadraticEase() {
  27913. _super.apply(this, arguments);
  27914. }
  27915. QuadraticEase.prototype.easeInCore = function (gradient) {
  27916. return (gradient * gradient);
  27917. };
  27918. return QuadraticEase;
  27919. })(EasingFunction);
  27920. BABYLON.QuadraticEase = QuadraticEase;
  27921. var QuarticEase = (function (_super) {
  27922. __extends(QuarticEase, _super);
  27923. function QuarticEase() {
  27924. _super.apply(this, arguments);
  27925. }
  27926. QuarticEase.prototype.easeInCore = function (gradient) {
  27927. return (gradient * gradient * gradient * gradient);
  27928. };
  27929. return QuarticEase;
  27930. })(EasingFunction);
  27931. BABYLON.QuarticEase = QuarticEase;
  27932. var QuinticEase = (function (_super) {
  27933. __extends(QuinticEase, _super);
  27934. function QuinticEase() {
  27935. _super.apply(this, arguments);
  27936. }
  27937. QuinticEase.prototype.easeInCore = function (gradient) {
  27938. return (gradient * gradient * gradient * gradient * gradient);
  27939. };
  27940. return QuinticEase;
  27941. })(EasingFunction);
  27942. BABYLON.QuinticEase = QuinticEase;
  27943. var SineEase = (function (_super) {
  27944. __extends(SineEase, _super);
  27945. function SineEase() {
  27946. _super.apply(this, arguments);
  27947. }
  27948. SineEase.prototype.easeInCore = function (gradient) {
  27949. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  27950. };
  27951. return SineEase;
  27952. })(EasingFunction);
  27953. BABYLON.SineEase = SineEase;
  27954. var BezierCurveEase = (function (_super) {
  27955. __extends(BezierCurveEase, _super);
  27956. function BezierCurveEase(x1, y1, x2, y2) {
  27957. if (x1 === void 0) { x1 = 0; }
  27958. if (y1 === void 0) { y1 = 0; }
  27959. if (x2 === void 0) { x2 = 1; }
  27960. if (y2 === void 0) { y2 = 1; }
  27961. _super.call(this);
  27962. this.x1 = x1;
  27963. this.y1 = y1;
  27964. this.x2 = x2;
  27965. this.y2 = y2;
  27966. }
  27967. BezierCurveEase.prototype.easeInCore = function (gradient) {
  27968. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  27969. };
  27970. return BezierCurveEase;
  27971. })(EasingFunction);
  27972. BABYLON.BezierCurveEase = BezierCurveEase;
  27973. })(BABYLON || (BABYLON = {}));
  27974. var BABYLON;
  27975. (function (BABYLON) {
  27976. var Bone = (function (_super) {
  27977. __extends(Bone, _super);
  27978. function Bone(name, skeleton, parentBone, matrix, restPose) {
  27979. _super.call(this, name, skeleton.getScene());
  27980. this.name = name;
  27981. this.children = new Array();
  27982. this.animations = new Array();
  27983. this._worldTransform = new BABYLON.Matrix();
  27984. this._absoluteTransform = new BABYLON.Matrix();
  27985. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  27986. this._skeleton = skeleton;
  27987. this._matrix = matrix;
  27988. this._baseMatrix = matrix;
  27989. this._restPose = restPose ? restPose : matrix.clone();
  27990. skeleton.bones.push(this);
  27991. if (parentBone) {
  27992. this._parent = parentBone;
  27993. parentBone.children.push(this);
  27994. }
  27995. else {
  27996. this._parent = null;
  27997. }
  27998. this._updateDifferenceMatrix();
  27999. }
  28000. // Members
  28001. Bone.prototype.getParent = function () {
  28002. return this._parent;
  28003. };
  28004. Bone.prototype.getLocalMatrix = function () {
  28005. return this._matrix;
  28006. };
  28007. Bone.prototype.getBaseMatrix = function () {
  28008. return this._baseMatrix;
  28009. };
  28010. Bone.prototype.getRestPose = function () {
  28011. return this._restPose;
  28012. };
  28013. Bone.prototype.returnToRest = function () {
  28014. this.updateMatrix(this._restPose.clone());
  28015. };
  28016. Bone.prototype.getWorldMatrix = function () {
  28017. return this._worldTransform;
  28018. };
  28019. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28020. return this._invertedAbsoluteTransform;
  28021. };
  28022. Bone.prototype.getAbsoluteTransform = function () {
  28023. return this._absoluteTransform;
  28024. };
  28025. // Methods
  28026. Bone.prototype.updateMatrix = function (matrix) {
  28027. this._baseMatrix = matrix.clone();
  28028. this._matrix = matrix.clone();
  28029. this._skeleton._markAsDirty();
  28030. this._updateDifferenceMatrix();
  28031. };
  28032. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28033. if (!rootMatrix) {
  28034. rootMatrix = this._baseMatrix;
  28035. }
  28036. if (this._parent) {
  28037. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28038. }
  28039. else {
  28040. this._absoluteTransform.copyFrom(rootMatrix);
  28041. }
  28042. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28043. for (var index = 0; index < this.children.length; index++) {
  28044. this.children[index]._updateDifferenceMatrix();
  28045. }
  28046. };
  28047. Bone.prototype.markAsDirty = function () {
  28048. this._currentRenderId++;
  28049. this._skeleton._markAsDirty();
  28050. };
  28051. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28052. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28053. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28054. // all animation may be coming from a library skeleton, so may need to create animation
  28055. if (this.animations.length === 0) {
  28056. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28057. this.animations[0].setKeys([]);
  28058. }
  28059. // get animation info / verify there is such a range from the source bone
  28060. var sourceRange = source.animations[0].getRange(rangeName);
  28061. if (!sourceRange) {
  28062. return false;
  28063. }
  28064. var from = sourceRange.from;
  28065. var to = sourceRange.to;
  28066. var sourceKeys = source.animations[0].getKeys();
  28067. // rescaling prep
  28068. var sourceBoneLength = source.length;
  28069. var sourceParent = source.getParent();
  28070. var parent = this.getParent();
  28071. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28072. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28073. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28074. var destKeys = this.animations[0].getKeys();
  28075. // loop vars declaration
  28076. var orig;
  28077. var origTranslation;
  28078. var mat;
  28079. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28080. orig = sourceKeys[key];
  28081. if (orig.frame >= from && orig.frame <= to) {
  28082. if (rescaleAsRequired) {
  28083. mat = orig.value.clone();
  28084. // scale based on parent ratio, when bone has parent
  28085. if (parentScalingReqd) {
  28086. origTranslation = mat.getTranslation();
  28087. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28088. }
  28089. else if (dimensionsScalingReqd) {
  28090. origTranslation = mat.getTranslation();
  28091. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28092. }
  28093. else {
  28094. mat = orig.value;
  28095. }
  28096. }
  28097. else {
  28098. mat = orig.value;
  28099. }
  28100. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28101. }
  28102. }
  28103. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28104. return true;
  28105. };
  28106. return Bone;
  28107. })(BABYLON.Node);
  28108. BABYLON.Bone = Bone;
  28109. })(BABYLON || (BABYLON = {}));
  28110. var BABYLON;
  28111. (function (BABYLON) {
  28112. var Skeleton = (function () {
  28113. function Skeleton(name, id, scene) {
  28114. this.name = name;
  28115. this.id = id;
  28116. this.bones = new Array();
  28117. this.needInitialSkinMatrix = false;
  28118. this._isDirty = true;
  28119. this._meshesWithPoseMatrix = new Array();
  28120. this._identity = BABYLON.Matrix.Identity();
  28121. this._ranges = {};
  28122. this.bones = [];
  28123. this._scene = scene;
  28124. scene.skeletons.push(this);
  28125. //make sure it will recalculate the matrix next time prepare is called.
  28126. this._isDirty = true;
  28127. }
  28128. // Members
  28129. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28130. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28131. return mesh._bonesTransformMatrices;
  28132. }
  28133. return this._transformMatrices;
  28134. };
  28135. Skeleton.prototype.getScene = function () {
  28136. return this._scene;
  28137. };
  28138. // Methods
  28139. /**
  28140. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28141. */
  28142. Skeleton.prototype.toString = function (fullDetails) {
  28143. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28144. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28145. if (fullDetails) {
  28146. ret += ", Ranges: {";
  28147. var first = true;
  28148. for (var name_1 in this._ranges) {
  28149. if (first) {
  28150. ret += ", ";
  28151. first = false;
  28152. }
  28153. ret += name_1;
  28154. }
  28155. ret += "}";
  28156. }
  28157. return ret;
  28158. };
  28159. /**
  28160. * Get bone's index searching by name
  28161. * @param {string} name is bone's name to search for
  28162. * @return {number} Indice of the bone. Returns -1 if not found
  28163. */
  28164. Skeleton.prototype.getBoneIndexByName = function (name) {
  28165. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28166. if (this.bones[boneIndex].name === name) {
  28167. return boneIndex;
  28168. }
  28169. }
  28170. return -1;
  28171. };
  28172. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28173. // check name not already in use
  28174. if (!this._ranges[name]) {
  28175. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28176. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28177. if (this.bones[i].animations[0]) {
  28178. this.bones[i].animations[0].createRange(name, from, to);
  28179. }
  28180. }
  28181. }
  28182. };
  28183. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28184. if (deleteFrames === void 0) { deleteFrames = true; }
  28185. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28186. if (this.bones[i].animations[0]) {
  28187. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28188. }
  28189. }
  28190. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28191. };
  28192. Skeleton.prototype.getAnimationRange = function (name) {
  28193. return this._ranges[name];
  28194. };
  28195. /**
  28196. * Returns as an Array, all AnimationRanges defined on this skeleton
  28197. */
  28198. Skeleton.prototype.getAnimationRanges = function () {
  28199. var animationRanges = [];
  28200. var name;
  28201. var i = 0;
  28202. for (name in this._ranges) {
  28203. animationRanges[i] = this._ranges[name];
  28204. i++;
  28205. }
  28206. return animationRanges;
  28207. };
  28208. /**
  28209. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28210. */
  28211. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28212. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28213. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28214. return false;
  28215. }
  28216. var ret = true;
  28217. var frameOffset = this._getHighestAnimationFrame() + 1;
  28218. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28219. var boneDict = {};
  28220. var sourceBones = source.bones;
  28221. var nBones;
  28222. var i;
  28223. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28224. boneDict[sourceBones[i].name] = sourceBones[i];
  28225. }
  28226. if (this.bones.length !== sourceBones.length) {
  28227. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28228. ret = false;
  28229. }
  28230. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28231. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28232. var boneName = this.bones[i].name;
  28233. var sourceBone = boneDict[boneName];
  28234. if (sourceBone) {
  28235. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28236. }
  28237. else {
  28238. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28239. ret = false;
  28240. }
  28241. }
  28242. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28243. var range = source.getAnimationRange(name);
  28244. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28245. return ret;
  28246. };
  28247. Skeleton.prototype.returnToRest = function () {
  28248. for (var index = 0; index < this.bones.length; index++) {
  28249. this.bones[index].returnToRest();
  28250. }
  28251. };
  28252. Skeleton.prototype._getHighestAnimationFrame = function () {
  28253. var ret = 0;
  28254. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28255. if (this.bones[i].animations[0]) {
  28256. var highest = this.bones[i].animations[0].getHighestFrame();
  28257. if (ret < highest) {
  28258. ret = highest;
  28259. }
  28260. }
  28261. }
  28262. return ret;
  28263. };
  28264. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28265. var range = this.getAnimationRange(name);
  28266. if (!range) {
  28267. return null;
  28268. }
  28269. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28270. };
  28271. Skeleton.prototype._markAsDirty = function () {
  28272. this._isDirty = true;
  28273. };
  28274. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28275. this._meshesWithPoseMatrix.push(mesh);
  28276. };
  28277. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28278. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28279. if (index > -1) {
  28280. this._meshesWithPoseMatrix.splice(index, 1);
  28281. }
  28282. };
  28283. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28284. for (var index = 0; index < this.bones.length; index++) {
  28285. var bone = this.bones[index];
  28286. var parentBone = bone.getParent();
  28287. if (parentBone) {
  28288. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28289. }
  28290. else {
  28291. if (initialSkinMatrix) {
  28292. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28293. }
  28294. else {
  28295. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28296. }
  28297. }
  28298. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28299. }
  28300. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28301. };
  28302. Skeleton.prototype.prepare = function () {
  28303. if (!this._isDirty) {
  28304. return;
  28305. }
  28306. if (this.needInitialSkinMatrix) {
  28307. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28308. var mesh = this._meshesWithPoseMatrix[index];
  28309. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28310. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28311. }
  28312. var poseMatrix = mesh.getPoseMatrix();
  28313. // Prepare bones
  28314. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28315. var bone = this.bones[boneIndex];
  28316. if (!bone.getParent()) {
  28317. var matrix = bone.getBaseMatrix();
  28318. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28319. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28320. }
  28321. }
  28322. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28323. }
  28324. }
  28325. else {
  28326. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28327. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28328. }
  28329. this._computeTransformMatrices(this._transformMatrices, null);
  28330. }
  28331. this._isDirty = false;
  28332. this._scene._activeBones.addCount(this.bones.length, false);
  28333. };
  28334. Skeleton.prototype.getAnimatables = function () {
  28335. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28336. this._animatables = [];
  28337. for (var index = 0; index < this.bones.length; index++) {
  28338. this._animatables.push(this.bones[index]);
  28339. }
  28340. }
  28341. return this._animatables;
  28342. };
  28343. Skeleton.prototype.clone = function (name, id) {
  28344. var result = new Skeleton(name, id || name, this._scene);
  28345. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28346. for (var index = 0; index < this.bones.length; index++) {
  28347. var source = this.bones[index];
  28348. var parentBone = null;
  28349. if (source.getParent()) {
  28350. var parentIndex = this.bones.indexOf(source.getParent());
  28351. parentBone = result.bones[parentIndex];
  28352. }
  28353. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28354. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28355. }
  28356. if (this._ranges) {
  28357. result._ranges = {};
  28358. for (var rangeName in this._ranges) {
  28359. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28360. }
  28361. }
  28362. this._isDirty = true;
  28363. return result;
  28364. };
  28365. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28366. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28367. this.bones.forEach(function (bone) {
  28368. bone.animations.forEach(function (animation) {
  28369. animation.enableBlending = true;
  28370. animation.blendingSpeed = blendingSpeed;
  28371. });
  28372. });
  28373. };
  28374. Skeleton.prototype.dispose = function () {
  28375. this._meshesWithPoseMatrix = [];
  28376. // Animations
  28377. this.getScene().stopAnimation(this);
  28378. // Remove from scene
  28379. this.getScene().removeSkeleton(this);
  28380. };
  28381. Skeleton.prototype.serialize = function () {
  28382. var serializationObject = {};
  28383. serializationObject.name = this.name;
  28384. serializationObject.id = this.id;
  28385. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  28386. serializationObject.bones = [];
  28387. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28388. for (var index = 0; index < this.bones.length; index++) {
  28389. var bone = this.bones[index];
  28390. var serializedBone = {
  28391. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  28392. name: bone.name,
  28393. matrix: bone.getLocalMatrix().toArray(),
  28394. rest: bone.getRestPose().toArray()
  28395. };
  28396. serializationObject.bones.push(serializedBone);
  28397. if (bone.length) {
  28398. serializedBone.length = bone.length;
  28399. }
  28400. if (bone.animations && bone.animations.length > 0) {
  28401. serializedBone.animation = bone.animations[0].serialize();
  28402. }
  28403. serializationObject.ranges = [];
  28404. for (var name in this._ranges) {
  28405. var range = {};
  28406. range.name = name;
  28407. range.from = this._ranges[name].from;
  28408. range.to = this._ranges[name].to;
  28409. serializationObject.ranges.push(range);
  28410. }
  28411. }
  28412. return serializationObject;
  28413. };
  28414. Skeleton.Parse = function (parsedSkeleton, scene) {
  28415. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  28416. if (parsedSkeleton.dimensionsAtRest) {
  28417. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  28418. }
  28419. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  28420. var index;
  28421. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  28422. var parsedBone = parsedSkeleton.bones[index];
  28423. var parentBone = null;
  28424. if (parsedBone.parentBoneIndex > -1) {
  28425. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  28426. }
  28427. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  28428. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  28429. if (parsedBone.length) {
  28430. bone.length = parsedBone.length;
  28431. }
  28432. if (parsedBone.animation) {
  28433. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  28434. }
  28435. }
  28436. // placed after bones, so createAnimationRange can cascade down
  28437. if (parsedSkeleton.ranges) {
  28438. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  28439. var data = parsedSkeleton.ranges[index];
  28440. skeleton.createAnimationRange(data.name, data.from, data.to);
  28441. }
  28442. }
  28443. return skeleton;
  28444. };
  28445. return Skeleton;
  28446. })();
  28447. BABYLON.Skeleton = Skeleton;
  28448. })(BABYLON || (BABYLON = {}));
  28449. var BABYLON;
  28450. (function (BABYLON) {
  28451. var PostProcess = (function () {
  28452. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  28453. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  28454. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28455. this.name = name;
  28456. this.width = -1;
  28457. this.height = -1;
  28458. /*
  28459. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  28460. Can only be used on a single postprocess or on the last one of a chain.
  28461. */
  28462. this.enablePixelPerfectMode = false;
  28463. this._reusable = false;
  28464. this._textures = new BABYLON.SmartArray(2);
  28465. this._currentRenderTextureInd = 0;
  28466. this._scaleRatio = new BABYLON.Vector2(1, 1);
  28467. // Events
  28468. /**
  28469. * An event triggered when the postprocess is activated.
  28470. * @type {BABYLON.Observable}
  28471. */
  28472. this.onActivateObservable = new BABYLON.Observable();
  28473. /**
  28474. * An event triggered when the postprocess changes its size.
  28475. * @type {BABYLON.Observable}
  28476. */
  28477. this.onSizeChangedObservable = new BABYLON.Observable();
  28478. /**
  28479. * An event triggered when the postprocess applies its effect.
  28480. * @type {BABYLON.Observable}
  28481. */
  28482. this.onApplyObservable = new BABYLON.Observable();
  28483. /**
  28484. * An event triggered before rendering the postprocess
  28485. * @type {BABYLON.Observable}
  28486. */
  28487. this.onBeforeRenderObservable = new BABYLON.Observable();
  28488. /**
  28489. * An event triggered after rendering the postprocess
  28490. * @type {BABYLON.Observable}
  28491. */
  28492. this.onAfterRenderObservable = new BABYLON.Observable();
  28493. if (camera != null) {
  28494. this._camera = camera;
  28495. this._scene = camera.getScene();
  28496. camera.attachPostProcess(this);
  28497. this._engine = this._scene.getEngine();
  28498. }
  28499. else {
  28500. this._engine = engine;
  28501. }
  28502. this._options = options;
  28503. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  28504. this._reusable = reusable || false;
  28505. this._textureType = textureType;
  28506. this._samplers = samplers || [];
  28507. this._samplers.push("textureSampler");
  28508. this._fragmentUrl = fragmentUrl;
  28509. this._parameters = parameters || [];
  28510. this._parameters.push("scale");
  28511. this.updateEffect(defines);
  28512. }
  28513. Object.defineProperty(PostProcess.prototype, "onActivate", {
  28514. set: function (callback) {
  28515. if (this._onActivateObserver) {
  28516. this.onActivateObservable.remove(this._onActivateObserver);
  28517. }
  28518. this._onActivateObserver = this.onActivateObservable.add(callback);
  28519. },
  28520. enumerable: true,
  28521. configurable: true
  28522. });
  28523. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  28524. set: function (callback) {
  28525. if (this._onSizeChangedObserver) {
  28526. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  28527. }
  28528. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  28529. },
  28530. enumerable: true,
  28531. configurable: true
  28532. });
  28533. Object.defineProperty(PostProcess.prototype, "onApply", {
  28534. set: function (callback) {
  28535. if (this._onApplyObserver) {
  28536. this.onApplyObservable.remove(this._onApplyObserver);
  28537. }
  28538. this._onApplyObserver = this.onApplyObservable.add(callback);
  28539. },
  28540. enumerable: true,
  28541. configurable: true
  28542. });
  28543. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  28544. set: function (callback) {
  28545. if (this._onBeforeRenderObserver) {
  28546. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28547. }
  28548. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28549. },
  28550. enumerable: true,
  28551. configurable: true
  28552. });
  28553. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  28554. set: function (callback) {
  28555. if (this._onAfterRenderObserver) {
  28556. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28557. }
  28558. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28559. },
  28560. enumerable: true,
  28561. configurable: true
  28562. });
  28563. PostProcess.prototype.updateEffect = function (defines) {
  28564. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  28565. };
  28566. PostProcess.prototype.isReusable = function () {
  28567. return this._reusable;
  28568. };
  28569. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  28570. PostProcess.prototype.markTextureDirty = function () {
  28571. this.width = -1;
  28572. };
  28573. PostProcess.prototype.activate = function (camera, sourceTexture) {
  28574. camera = camera || this._camera;
  28575. var scene = camera.getScene();
  28576. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  28577. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  28578. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  28579. var desiredWidth = this._options.width || requiredWidth;
  28580. var desiredHeight = this._options.height || requiredHeight;
  28581. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  28582. if (!this._options.width) {
  28583. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  28584. }
  28585. if (!this._options.height) {
  28586. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  28587. }
  28588. }
  28589. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  28590. if (this._textures.length > 0) {
  28591. for (var i = 0; i < this._textures.length; i++) {
  28592. this._engine._releaseTexture(this._textures.data[i]);
  28593. }
  28594. this._textures.reset();
  28595. }
  28596. this.width = desiredWidth;
  28597. this.height = desiredHeight;
  28598. 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 }));
  28599. if (this._reusable) {
  28600. 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 }));
  28601. }
  28602. this.onSizeChangedObservable.notifyObservers(this);
  28603. }
  28604. if (this.enablePixelPerfectMode) {
  28605. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  28606. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  28607. }
  28608. else {
  28609. this._scaleRatio.copyFromFloats(1, 1);
  28610. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  28611. }
  28612. this.onActivateObservable.notifyObservers(camera);
  28613. // Clear
  28614. if (this.clearColor) {
  28615. this._engine.clear(this.clearColor, true, true);
  28616. }
  28617. else {
  28618. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  28619. }
  28620. if (this._reusable) {
  28621. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  28622. }
  28623. };
  28624. Object.defineProperty(PostProcess.prototype, "isSupported", {
  28625. get: function () {
  28626. return this._effect.isSupported;
  28627. },
  28628. enumerable: true,
  28629. configurable: true
  28630. });
  28631. PostProcess.prototype.apply = function () {
  28632. // Check
  28633. if (!this._effect.isReady())
  28634. return null;
  28635. // States
  28636. this._engine.enableEffect(this._effect);
  28637. this._engine.setState(false);
  28638. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28639. this._engine.setDepthBuffer(false);
  28640. this._engine.setDepthWrite(false);
  28641. // Texture
  28642. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  28643. // Parameters
  28644. this._effect.setVector2("scale", this._scaleRatio);
  28645. this.onApplyObservable.notifyObservers(this._effect);
  28646. return this._effect;
  28647. };
  28648. PostProcess.prototype.dispose = function (camera) {
  28649. camera = camera || this._camera;
  28650. if (this._textures.length > 0) {
  28651. for (var i = 0; i < this._textures.length; i++) {
  28652. this._engine._releaseTexture(this._textures.data[i]);
  28653. }
  28654. this._textures.reset();
  28655. }
  28656. if (!camera) {
  28657. return;
  28658. }
  28659. camera.detachPostProcess(this);
  28660. var index = camera._postProcesses.indexOf(this);
  28661. if (index === 0 && camera._postProcesses.length > 0) {
  28662. this._camera._postProcesses[0].markTextureDirty();
  28663. }
  28664. this.onActivateObservable.clear();
  28665. this.onAfterRenderObservable.clear();
  28666. this.onApplyObservable.clear();
  28667. this.onBeforeRenderObservable.clear();
  28668. this.onSizeChangedObservable.clear();
  28669. };
  28670. return PostProcess;
  28671. })();
  28672. BABYLON.PostProcess = PostProcess;
  28673. })(BABYLON || (BABYLON = {}));
  28674. var BABYLON;
  28675. (function (BABYLON) {
  28676. var PostProcessManager = (function () {
  28677. function PostProcessManager(scene) {
  28678. this._vertexBuffers = {};
  28679. this._scene = scene;
  28680. }
  28681. PostProcessManager.prototype._prepareBuffers = function () {
  28682. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28683. return;
  28684. }
  28685. // VBO
  28686. var vertices = [];
  28687. vertices.push(1, 1);
  28688. vertices.push(-1, 1);
  28689. vertices.push(-1, -1);
  28690. vertices.push(1, -1);
  28691. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28692. // Indices
  28693. var indices = [];
  28694. indices.push(0);
  28695. indices.push(1);
  28696. indices.push(2);
  28697. indices.push(0);
  28698. indices.push(2);
  28699. indices.push(3);
  28700. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28701. };
  28702. // Methods
  28703. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28704. var postProcesses = this._scene.activeCamera._postProcesses;
  28705. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28706. return false;
  28707. }
  28708. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28709. return true;
  28710. };
  28711. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28712. var engine = this._scene.getEngine();
  28713. for (var index = 0; index < postProcesses.length; index++) {
  28714. if (index < postProcesses.length - 1) {
  28715. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28716. }
  28717. else {
  28718. if (targetTexture) {
  28719. engine.bindFramebuffer(targetTexture);
  28720. }
  28721. else {
  28722. engine.restoreDefaultFramebuffer();
  28723. }
  28724. }
  28725. var pp = postProcesses[index];
  28726. var effect = pp.apply();
  28727. if (effect) {
  28728. pp.onBeforeRenderObservable.notifyObservers(effect);
  28729. // VBOs
  28730. this._prepareBuffers();
  28731. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28732. // Draw order
  28733. engine.draw(true, 0, 6);
  28734. pp.onAfterRenderObservable.notifyObservers(effect);
  28735. }
  28736. }
  28737. // Restore depth buffer
  28738. engine.setDepthBuffer(true);
  28739. engine.setDepthWrite(true);
  28740. };
  28741. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28742. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28743. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28744. return;
  28745. }
  28746. var engine = this._scene.getEngine();
  28747. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28748. if (index < len - 1) {
  28749. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28750. }
  28751. else {
  28752. if (targetTexture) {
  28753. engine.bindFramebuffer(targetTexture, faceIndex);
  28754. }
  28755. else {
  28756. engine.restoreDefaultFramebuffer();
  28757. }
  28758. }
  28759. if (doNotPresent) {
  28760. break;
  28761. }
  28762. var pp = postProcesses[index];
  28763. var effect = pp.apply();
  28764. if (effect) {
  28765. pp.onBeforeRenderObservable.notifyObservers(effect);
  28766. // VBOs
  28767. this._prepareBuffers();
  28768. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28769. // Draw order
  28770. engine.draw(true, 0, 6);
  28771. pp.onAfterRenderObservable.notifyObservers(effect);
  28772. }
  28773. }
  28774. // Restore depth buffer
  28775. engine.setDepthBuffer(true);
  28776. engine.setDepthWrite(true);
  28777. };
  28778. PostProcessManager.prototype.dispose = function () {
  28779. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28780. if (buffer) {
  28781. buffer.dispose();
  28782. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28783. }
  28784. if (this._indexBuffer) {
  28785. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28786. this._indexBuffer = null;
  28787. }
  28788. };
  28789. return PostProcessManager;
  28790. })();
  28791. BABYLON.PostProcessManager = PostProcessManager;
  28792. })(BABYLON || (BABYLON = {}));
  28793. var BABYLON;
  28794. (function (BABYLON) {
  28795. var PassPostProcess = (function (_super) {
  28796. __extends(PassPostProcess, _super);
  28797. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  28798. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  28799. }
  28800. return PassPostProcess;
  28801. })(BABYLON.PostProcess);
  28802. BABYLON.PassPostProcess = PassPostProcess;
  28803. })(BABYLON || (BABYLON = {}));
  28804. var BABYLON;
  28805. (function (BABYLON) {
  28806. /**
  28807. * This is a holder class for the physics joint created by the physics plugin.
  28808. * It holds a set of functions to control the underlying joint.
  28809. */
  28810. var PhysicsJoint = (function () {
  28811. function PhysicsJoint(type, jointData) {
  28812. this.type = type;
  28813. this.jointData = jointData;
  28814. jointData.nativeParams = jointData.nativeParams || {};
  28815. }
  28816. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  28817. get: function () {
  28818. return this._physicsJoint;
  28819. },
  28820. set: function (newJoint) {
  28821. if (this._physicsJoint) {
  28822. }
  28823. this._physicsJoint = newJoint;
  28824. },
  28825. enumerable: true,
  28826. configurable: true
  28827. });
  28828. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  28829. set: function (physicsPlugin) {
  28830. this._physicsPlugin = physicsPlugin;
  28831. },
  28832. enumerable: true,
  28833. configurable: true
  28834. });
  28835. /**
  28836. * Execute a function that is physics-plugin specific.
  28837. * @param {Function} func the function that will be executed.
  28838. * It accepts two parameters: the physics world and the physics joint.
  28839. */
  28840. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  28841. func(this._physicsPlugin.world, this._physicsJoint);
  28842. };
  28843. //TODO check if the native joints are the same
  28844. //Joint Types
  28845. PhysicsJoint.DistanceJoint = 0;
  28846. PhysicsJoint.HingeJoint = 1;
  28847. PhysicsJoint.BallAndSocketJoint = 2;
  28848. PhysicsJoint.WheelJoint = 3;
  28849. PhysicsJoint.SliderJoint = 4;
  28850. //OIMO
  28851. PhysicsJoint.PrismaticJoint = 5;
  28852. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  28853. PhysicsJoint.UniversalJoint = 6;
  28854. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  28855. //Cannon
  28856. //Similar to a Ball-Joint. Different in params
  28857. PhysicsJoint.PointToPointJoint = 8;
  28858. //Cannon only at the moment
  28859. PhysicsJoint.SpringJoint = 9;
  28860. PhysicsJoint.LockJoint = 10;
  28861. return PhysicsJoint;
  28862. })();
  28863. BABYLON.PhysicsJoint = PhysicsJoint;
  28864. /**
  28865. * A class representing a physics distance joint.
  28866. */
  28867. var DistanceJoint = (function (_super) {
  28868. __extends(DistanceJoint, _super);
  28869. function DistanceJoint(jointData) {
  28870. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  28871. }
  28872. /**
  28873. * Update the predefined distance.
  28874. */
  28875. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  28876. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  28877. };
  28878. return DistanceJoint;
  28879. })(PhysicsJoint);
  28880. BABYLON.DistanceJoint = DistanceJoint;
  28881. var MotorEnabledJoint = (function (_super) {
  28882. __extends(MotorEnabledJoint, _super);
  28883. function MotorEnabledJoint(type, jointData) {
  28884. _super.call(this, type, jointData);
  28885. }
  28886. /**
  28887. * Set the motor values.
  28888. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28889. * @param {number} force the force to apply
  28890. * @param {number} maxForce max force for this motor.
  28891. */
  28892. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  28893. this._physicsPlugin.setMotor(this, force, maxForce);
  28894. };
  28895. /**
  28896. * Set the motor's limits.
  28897. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28898. */
  28899. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28900. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28901. };
  28902. return MotorEnabledJoint;
  28903. })(PhysicsJoint);
  28904. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  28905. /**
  28906. * This class represents a single hinge physics joint
  28907. */
  28908. var HingeJoint = (function (_super) {
  28909. __extends(HingeJoint, _super);
  28910. function HingeJoint(jointData) {
  28911. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  28912. }
  28913. /**
  28914. * Set the motor values.
  28915. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28916. * @param {number} force the force to apply
  28917. * @param {number} maxForce max force for this motor.
  28918. */
  28919. HingeJoint.prototype.setMotor = function (force, maxForce) {
  28920. this._physicsPlugin.setMotor(this, force, maxForce);
  28921. };
  28922. /**
  28923. * Set the motor's limits.
  28924. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28925. */
  28926. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  28927. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  28928. };
  28929. return HingeJoint;
  28930. })(MotorEnabledJoint);
  28931. BABYLON.HingeJoint = HingeJoint;
  28932. /**
  28933. * This class represents a dual hinge physics joint (same as wheel joint)
  28934. */
  28935. var Hinge2Joint = (function (_super) {
  28936. __extends(Hinge2Joint, _super);
  28937. function Hinge2Joint(jointData) {
  28938. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  28939. }
  28940. /**
  28941. * Set the motor values.
  28942. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28943. * @param {number} force the force to apply
  28944. * @param {number} maxForce max force for this motor.
  28945. * @param {motorIndex} the motor's index, 0 or 1.
  28946. */
  28947. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  28948. if (motorIndex === void 0) { motorIndex = 0; }
  28949. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  28950. };
  28951. /**
  28952. * Set the motor limits.
  28953. * Attention, this function is plugin specific. Engines won't react 100% the same.
  28954. * @param {number} upperLimit the upper limit
  28955. * @param {number} lowerLimit lower limit
  28956. * @param {motorIndex} the motor's index, 0 or 1.
  28957. */
  28958. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  28959. if (motorIndex === void 0) { motorIndex = 0; }
  28960. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  28961. };
  28962. return Hinge2Joint;
  28963. })(MotorEnabledJoint);
  28964. BABYLON.Hinge2Joint = Hinge2Joint;
  28965. })(BABYLON || (BABYLON = {}));
  28966. var BABYLON;
  28967. (function (BABYLON) {
  28968. var PhysicsImpostor = (function () {
  28969. function PhysicsImpostor(object, type, _options, _scene) {
  28970. var _this = this;
  28971. if (_options === void 0) { _options = { mass: 0 }; }
  28972. this.object = object;
  28973. this.type = type;
  28974. this._options = _options;
  28975. this._scene = _scene;
  28976. this._bodyUpdateRequired = false;
  28977. this._onBeforePhysicsStepCallbacks = new Array();
  28978. this._onAfterPhysicsStepCallbacks = new Array();
  28979. this._onPhysicsCollideCallbacks = [];
  28980. this._deltaPosition = BABYLON.Vector3.Zero();
  28981. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  28982. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  28983. /**
  28984. * this function is executed by the physics engine.
  28985. */
  28986. this.beforeStep = function () {
  28987. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  28988. //conjugate deltaRotation
  28989. if (_this._deltaRotationConjugated) {
  28990. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  28991. }
  28992. else {
  28993. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  28994. }
  28995. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  28996. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  28997. func(_this);
  28998. });
  28999. };
  29000. /**
  29001. * this function is executed by the physics engine.
  29002. */
  29003. this.afterStep = function () {
  29004. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29005. func(_this);
  29006. });
  29007. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29008. _this.object.position.addInPlace(_this._deltaPosition);
  29009. if (_this._deltaRotation) {
  29010. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29011. }
  29012. };
  29013. //event and body object due to cannon's event-based architecture.
  29014. this.onCollide = function (e) {
  29015. if (!_this._onPhysicsCollideCallbacks.length)
  29016. return;
  29017. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29018. if (otherImpostor) {
  29019. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29020. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29021. }).forEach(function (obj) {
  29022. obj.callback(_this, otherImpostor);
  29023. });
  29024. }
  29025. };
  29026. //sanity check!
  29027. if (!this.object) {
  29028. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29029. return;
  29030. }
  29031. //legacy support for old syntax.
  29032. if (!this._scene && object.getScene) {
  29033. this._scene = object.getScene();
  29034. }
  29035. this._physicsEngine = this._scene.getPhysicsEngine();
  29036. if (!this._physicsEngine) {
  29037. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29038. }
  29039. else {
  29040. //set the object's quaternion, if not set
  29041. if (!this.object.rotationQuaternion) {
  29042. if (this.object.rotation) {
  29043. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29044. }
  29045. else {
  29046. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29047. }
  29048. }
  29049. //default options params
  29050. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29051. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29052. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29053. this._joints = [];
  29054. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29055. if (!this.object.parent) {
  29056. this._init();
  29057. }
  29058. }
  29059. }
  29060. /**
  29061. * This function will completly initialize this impostor.
  29062. * It will create a new body - but only if this mesh has no parent.
  29063. * If it has, this impostor will not be used other than to define the impostor
  29064. * of the child mesh.
  29065. */
  29066. PhysicsImpostor.prototype._init = function () {
  29067. this._physicsEngine.removeImpostor(this);
  29068. this.physicsBody = null;
  29069. this._parent = this._parent || this._getPhysicsParent();
  29070. if (!this.parent) {
  29071. this._physicsEngine.addImpostor(this);
  29072. }
  29073. };
  29074. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29075. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29076. var parentMesh = this.object.parent;
  29077. return parentMesh.physicsImpostor;
  29078. }
  29079. return;
  29080. };
  29081. /**
  29082. * Should a new body be generated.
  29083. */
  29084. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29085. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29086. };
  29087. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29088. this.forceUpdate();
  29089. };
  29090. /**
  29091. * Force a regeneration of this or the parent's impostor's body.
  29092. * Use under cautious - This will remove all joints already implemented.
  29093. */
  29094. PhysicsImpostor.prototype.forceUpdate = function () {
  29095. this._init();
  29096. if (this.parent) {
  29097. this.parent.forceUpdate();
  29098. }
  29099. };
  29100. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29101. /*public get mesh(): AbstractMesh {
  29102. return this._mesh;
  29103. }*/
  29104. /**
  29105. * Gets the body that holds this impostor. Either its own, or its parent.
  29106. */
  29107. get: function () {
  29108. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29109. },
  29110. /**
  29111. * Set the physics body. Used mainly by the physics engine/plugin
  29112. */
  29113. set: function (physicsBody) {
  29114. if (this._physicsBody) {
  29115. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29116. }
  29117. this._physicsBody = physicsBody;
  29118. this.resetUpdateFlags();
  29119. },
  29120. enumerable: true,
  29121. configurable: true
  29122. });
  29123. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29124. get: function () {
  29125. return this._parent;
  29126. },
  29127. enumerable: true,
  29128. configurable: true
  29129. });
  29130. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29131. this._bodyUpdateRequired = false;
  29132. };
  29133. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29134. if (this.object.getBoundingInfo) {
  29135. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29136. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29137. }
  29138. else {
  29139. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29140. }
  29141. };
  29142. PhysicsImpostor.prototype.getObjectCenter = function () {
  29143. if (this.object.getBoundingInfo) {
  29144. return this.object.getBoundingInfo().boundingBox.center;
  29145. }
  29146. else {
  29147. return this.object.position;
  29148. }
  29149. };
  29150. /**
  29151. * Get a specific parametes from the options parameter.
  29152. */
  29153. PhysicsImpostor.prototype.getParam = function (paramName) {
  29154. return this._options[paramName];
  29155. };
  29156. /**
  29157. * Sets a specific parameter in the options given to the physics plugin
  29158. */
  29159. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29160. this._options[paramName] = value;
  29161. this._bodyUpdateRequired = true;
  29162. };
  29163. /**
  29164. * Specifically change the body's mass option. Won't recreate the physics body object
  29165. */
  29166. PhysicsImpostor.prototype.setMass = function (mass) {
  29167. if (this.getParam("mass") !== mass) {
  29168. this.setParam("mass", mass);
  29169. }
  29170. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29171. };
  29172. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29173. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29174. };
  29175. /**
  29176. * Set the body's linear velocity.
  29177. */
  29178. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29179. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29180. };
  29181. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29182. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29183. };
  29184. /**
  29185. * Set the body's linear velocity.
  29186. */
  29187. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29188. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29189. };
  29190. /**
  29191. * Execute a function with the physics plugin native code.
  29192. * Provide a function the will have two variables - the world object and the physics body object.
  29193. */
  29194. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29195. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29196. };
  29197. /**
  29198. * Register a function that will be executed before the physics world is stepping forward.
  29199. */
  29200. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29201. this._onBeforePhysicsStepCallbacks.push(func);
  29202. };
  29203. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29204. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29205. if (index > -1) {
  29206. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29207. }
  29208. else {
  29209. BABYLON.Tools.Warn("Function to remove was not found");
  29210. }
  29211. };
  29212. /**
  29213. * Register a function that will be executed after the physics step
  29214. */
  29215. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29216. this._onAfterPhysicsStepCallbacks.push(func);
  29217. };
  29218. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29219. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29220. if (index > -1) {
  29221. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29222. }
  29223. else {
  29224. BABYLON.Tools.Warn("Function to remove was not found");
  29225. }
  29226. };
  29227. /**
  29228. * register a function that will be executed when this impostor collides against a different body.
  29229. */
  29230. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29231. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29232. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29233. };
  29234. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29235. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29236. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29237. if (index > -1) {
  29238. this._onPhysicsCollideCallbacks.splice(index, 1);
  29239. }
  29240. else {
  29241. BABYLON.Tools.Warn("Function to remove was not found");
  29242. }
  29243. };
  29244. /**
  29245. * Apply a force
  29246. */
  29247. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29248. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29249. };
  29250. /**
  29251. * Apply an impulse
  29252. */
  29253. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29254. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29255. };
  29256. /**
  29257. * A help function to create a joint.
  29258. */
  29259. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29260. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29261. this.addJoint(otherImpostor, joint);
  29262. };
  29263. /**
  29264. * Add a joint to this impostor with a different impostor.
  29265. */
  29266. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29267. this._joints.push({
  29268. otherImpostor: otherImpostor,
  29269. joint: joint
  29270. });
  29271. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29272. };
  29273. /**
  29274. * Will keep this body still, in a sleep mode.
  29275. */
  29276. PhysicsImpostor.prototype.sleep = function () {
  29277. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29278. };
  29279. /**
  29280. * Wake the body up.
  29281. */
  29282. PhysicsImpostor.prototype.wakeUp = function () {
  29283. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29284. };
  29285. PhysicsImpostor.prototype.clone = function (newObject) {
  29286. if (!newObject)
  29287. return null;
  29288. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29289. };
  29290. PhysicsImpostor.prototype.dispose = function () {
  29291. var _this = this;
  29292. //no dispose if no physics engine is available.
  29293. if (!this._physicsEngine) {
  29294. return;
  29295. }
  29296. this._joints.forEach(function (j) {
  29297. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29298. });
  29299. //dispose the physics body
  29300. this._physicsEngine.removeImpostor(this);
  29301. if (this.parent) {
  29302. this.parent.forceUpdate();
  29303. }
  29304. else {
  29305. }
  29306. };
  29307. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29308. this._deltaPosition.copyFrom(position);
  29309. };
  29310. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29311. if (!this._deltaRotation) {
  29312. this._deltaRotation = new BABYLON.Quaternion();
  29313. }
  29314. this._deltaRotation.copyFrom(rotation);
  29315. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29316. };
  29317. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29318. //Impostor types
  29319. PhysicsImpostor.NoImpostor = 0;
  29320. PhysicsImpostor.SphereImpostor = 1;
  29321. PhysicsImpostor.BoxImpostor = 2;
  29322. PhysicsImpostor.PlaneImpostor = 3;
  29323. PhysicsImpostor.MeshImpostor = 4;
  29324. PhysicsImpostor.CylinderImpostor = 7;
  29325. PhysicsImpostor.ParticleImpostor = 8;
  29326. PhysicsImpostor.HeightmapImpostor = 9;
  29327. return PhysicsImpostor;
  29328. })();
  29329. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29330. })(BABYLON || (BABYLON = {}));
  29331. var BABYLON;
  29332. (function (BABYLON) {
  29333. var PhysicsEngine = (function () {
  29334. function PhysicsEngine(gravity, _physicsPlugin) {
  29335. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29336. this._physicsPlugin = _physicsPlugin;
  29337. //new methods and parameters
  29338. this._impostors = [];
  29339. this._joints = [];
  29340. if (!this._physicsPlugin.isSupported()) {
  29341. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29342. + "Please make sure it is included.");
  29343. }
  29344. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29345. this.setGravity(gravity);
  29346. this.setTimeStep();
  29347. }
  29348. PhysicsEngine.prototype.setGravity = function (gravity) {
  29349. this.gravity = gravity;
  29350. this._physicsPlugin.setGravity(this.gravity);
  29351. };
  29352. /**
  29353. * Set the time step of the physics engine.
  29354. * default is 1/60.
  29355. * To slow it down, enter 1/600 for example.
  29356. * To speed it up, 1/30
  29357. * @param {number} newTimeStep the new timestep to apply to this world.
  29358. */
  29359. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29360. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29361. this._physicsPlugin.setTimeStep(newTimeStep);
  29362. };
  29363. PhysicsEngine.prototype.dispose = function () {
  29364. this._impostors.forEach(function (impostor) {
  29365. impostor.dispose();
  29366. });
  29367. this._physicsPlugin.dispose();
  29368. };
  29369. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  29370. return this._physicsPlugin.name;
  29371. };
  29372. /**
  29373. * Adding a new impostor for the impostor tracking.
  29374. * This will be done by the impostor itself.
  29375. * @param {PhysicsImpostor} impostor the impostor to add
  29376. */
  29377. PhysicsEngine.prototype.addImpostor = function (impostor) {
  29378. impostor.uniqueId = this._impostors.push(impostor);
  29379. //if no parent, generate the body
  29380. if (!impostor.parent) {
  29381. this._physicsPlugin.generatePhysicsBody(impostor);
  29382. }
  29383. };
  29384. /**
  29385. * Remove an impostor from the engine.
  29386. * This impostor and its mesh will not longer be updated by the physics engine.
  29387. * @param {PhysicsImpostor} impostor the impostor to remove
  29388. */
  29389. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  29390. var index = this._impostors.indexOf(impostor);
  29391. if (index > -1) {
  29392. var removed = this._impostors.splice(index, 1);
  29393. //Is it needed?
  29394. if (removed.length) {
  29395. //this will also remove it from the world.
  29396. removed[0].physicsBody = null;
  29397. }
  29398. }
  29399. };
  29400. /**
  29401. * Add a joint to the physics engine
  29402. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  29403. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  29404. * @param {PhysicsJoint} the joint that will connect both impostors.
  29405. */
  29406. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  29407. var impostorJoint = {
  29408. mainImpostor: mainImpostor,
  29409. connectedImpostor: connectedImpostor,
  29410. joint: joint
  29411. };
  29412. joint.physicsPlugin = this._physicsPlugin;
  29413. this._joints.push(impostorJoint);
  29414. this._physicsPlugin.generateJoint(impostorJoint);
  29415. };
  29416. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  29417. var matchingJoints = this._joints.filter(function (impostorJoint) {
  29418. return (impostorJoint.connectedImpostor === connectedImpostor
  29419. && impostorJoint.joint === joint
  29420. && impostorJoint.mainImpostor === mainImpostor);
  29421. });
  29422. if (matchingJoints.length) {
  29423. this._physicsPlugin.removeJoint(matchingJoints[0]);
  29424. }
  29425. };
  29426. /**
  29427. * Called by the scene. no need to call it.
  29428. */
  29429. PhysicsEngine.prototype._step = function (delta) {
  29430. var _this = this;
  29431. //check if any mesh has no body / requires an update
  29432. this._impostors.forEach(function (impostor) {
  29433. if (impostor.isBodyInitRequired()) {
  29434. _this._physicsPlugin.generatePhysicsBody(impostor);
  29435. }
  29436. });
  29437. if (delta > 0.1) {
  29438. delta = 0.1;
  29439. }
  29440. else if (delta <= 0) {
  29441. delta = 1.0 / 60.0;
  29442. }
  29443. this._physicsPlugin.executeStep(delta, this._impostors);
  29444. };
  29445. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  29446. return this._physicsPlugin;
  29447. };
  29448. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  29449. for (var i = 0; i < this._impostors.length; ++i) {
  29450. if (this._impostors[i].object === object) {
  29451. return this._impostors[i];
  29452. }
  29453. }
  29454. };
  29455. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  29456. for (var i = 0; i < this._impostors.length; ++i) {
  29457. if (this._impostors[i].physicsBody === body) {
  29458. return this._impostors[i];
  29459. }
  29460. }
  29461. };
  29462. // Statics, Legacy support.
  29463. /**
  29464. * @Deprecated
  29465. *
  29466. */
  29467. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  29468. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  29469. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  29470. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  29471. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  29472. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  29473. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  29474. PhysicsEngine.CapsuleImpostor = -1;
  29475. PhysicsEngine.ConeImpostor = -1;
  29476. PhysicsEngine.ConvexHullImpostor = -1;
  29477. PhysicsEngine.Epsilon = 0.001;
  29478. return PhysicsEngine;
  29479. })();
  29480. BABYLON.PhysicsEngine = PhysicsEngine;
  29481. })(BABYLON || (BABYLON = {}));
  29482. var BABYLON;
  29483. (function (BABYLON) {
  29484. var VertexData = (function () {
  29485. function VertexData() {
  29486. }
  29487. VertexData.prototype.set = function (data, kind) {
  29488. switch (kind) {
  29489. case BABYLON.VertexBuffer.PositionKind:
  29490. this.positions = data;
  29491. break;
  29492. case BABYLON.VertexBuffer.NormalKind:
  29493. this.normals = data;
  29494. break;
  29495. case BABYLON.VertexBuffer.UVKind:
  29496. this.uvs = data;
  29497. break;
  29498. case BABYLON.VertexBuffer.UV2Kind:
  29499. this.uvs2 = data;
  29500. break;
  29501. case BABYLON.VertexBuffer.UV3Kind:
  29502. this.uvs3 = data;
  29503. break;
  29504. case BABYLON.VertexBuffer.UV4Kind:
  29505. this.uvs4 = data;
  29506. break;
  29507. case BABYLON.VertexBuffer.UV5Kind:
  29508. this.uvs5 = data;
  29509. break;
  29510. case BABYLON.VertexBuffer.UV6Kind:
  29511. this.uvs6 = data;
  29512. break;
  29513. case BABYLON.VertexBuffer.ColorKind:
  29514. this.colors = data;
  29515. break;
  29516. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29517. this.matricesIndices = data;
  29518. break;
  29519. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29520. this.matricesWeights = data;
  29521. break;
  29522. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29523. this.matricesIndicesExtra = data;
  29524. break;
  29525. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29526. this.matricesWeightsExtra = data;
  29527. break;
  29528. }
  29529. };
  29530. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29531. this._applyTo(mesh, updatable);
  29532. };
  29533. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29534. this._applyTo(geometry, updatable);
  29535. };
  29536. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29537. this._update(mesh);
  29538. };
  29539. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29540. this._update(geometry);
  29541. };
  29542. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29543. if (this.positions) {
  29544. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29545. }
  29546. if (this.normals) {
  29547. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29548. }
  29549. if (this.uvs) {
  29550. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29551. }
  29552. if (this.uvs2) {
  29553. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29554. }
  29555. if (this.uvs3) {
  29556. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29557. }
  29558. if (this.uvs4) {
  29559. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29560. }
  29561. if (this.uvs5) {
  29562. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29563. }
  29564. if (this.uvs6) {
  29565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29566. }
  29567. if (this.colors) {
  29568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29569. }
  29570. if (this.matricesIndices) {
  29571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29572. }
  29573. if (this.matricesWeights) {
  29574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29575. }
  29576. if (this.matricesIndicesExtra) {
  29577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29578. }
  29579. if (this.matricesWeightsExtra) {
  29580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29581. }
  29582. if (this.indices) {
  29583. meshOrGeometry.setIndices(this.indices);
  29584. }
  29585. };
  29586. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29587. if (this.positions) {
  29588. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29589. }
  29590. if (this.normals) {
  29591. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29592. }
  29593. if (this.uvs) {
  29594. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29595. }
  29596. if (this.uvs2) {
  29597. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29598. }
  29599. if (this.uvs3) {
  29600. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29601. }
  29602. if (this.uvs4) {
  29603. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29604. }
  29605. if (this.uvs5) {
  29606. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29607. }
  29608. if (this.uvs6) {
  29609. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29610. }
  29611. if (this.colors) {
  29612. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29613. }
  29614. if (this.matricesIndices) {
  29615. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29616. }
  29617. if (this.matricesWeights) {
  29618. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29619. }
  29620. if (this.matricesIndicesExtra) {
  29621. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29622. }
  29623. if (this.matricesWeightsExtra) {
  29624. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29625. }
  29626. if (this.indices) {
  29627. meshOrGeometry.setIndices(this.indices);
  29628. }
  29629. };
  29630. VertexData.prototype.transform = function (matrix) {
  29631. var transformed = BABYLON.Vector3.Zero();
  29632. var index;
  29633. if (this.positions) {
  29634. var position = BABYLON.Vector3.Zero();
  29635. for (index = 0; index < this.positions.length; index += 3) {
  29636. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29637. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29638. this.positions[index] = transformed.x;
  29639. this.positions[index + 1] = transformed.y;
  29640. this.positions[index + 2] = transformed.z;
  29641. }
  29642. }
  29643. if (this.normals) {
  29644. var normal = BABYLON.Vector3.Zero();
  29645. for (index = 0; index < this.normals.length; index += 3) {
  29646. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29647. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29648. this.normals[index] = transformed.x;
  29649. this.normals[index + 1] = transformed.y;
  29650. this.normals[index + 2] = transformed.z;
  29651. }
  29652. }
  29653. };
  29654. VertexData.prototype.merge = function (other) {
  29655. if (other.indices) {
  29656. if (!this.indices) {
  29657. this.indices = [];
  29658. }
  29659. var offset = this.positions ? this.positions.length / 3 : 0;
  29660. for (var index = 0; index < other.indices.length; index++) {
  29661. //TODO check type - if Int32Array!
  29662. this.indices.push(other.indices[index] + offset);
  29663. }
  29664. }
  29665. this.positions = this._mergeElement(this.positions, other.positions);
  29666. this.normals = this._mergeElement(this.normals, other.normals);
  29667. this.uvs = this._mergeElement(this.uvs, other.uvs);
  29668. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  29669. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  29670. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  29671. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  29672. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  29673. this.colors = this._mergeElement(this.colors, other.colors);
  29674. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  29675. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  29676. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  29677. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  29678. };
  29679. VertexData.prototype._mergeElement = function (source, other) {
  29680. if (!other)
  29681. return source;
  29682. if (!source)
  29683. return other;
  29684. var len = other.length + source.length;
  29685. var isSrcTypedArray = source instanceof Float32Array;
  29686. var isOthTypedArray = other instanceof Float32Array;
  29687. // use non-loop method when the source is Float32Array
  29688. if (isSrcTypedArray) {
  29689. var ret32 = new Float32Array(len);
  29690. ret32.set(source);
  29691. ret32.set(other, source.length);
  29692. return ret32;
  29693. }
  29694. else if (!isOthTypedArray) {
  29695. return source.concat(other);
  29696. }
  29697. else {
  29698. var ret = source.slice(0); // copy source to a separate array
  29699. for (var i = 0, len = other.length; i < len; i++) {
  29700. ret.push(other[i]);
  29701. }
  29702. return ret;
  29703. }
  29704. };
  29705. VertexData.prototype.serialize = function () {
  29706. var serializationObject = this.serialize();
  29707. if (this.positions) {
  29708. serializationObject.positions = this.positions;
  29709. }
  29710. if (this.normals) {
  29711. serializationObject.normals = this.normals;
  29712. }
  29713. if (this.uvs) {
  29714. serializationObject.uvs = this.uvs;
  29715. }
  29716. if (this.uvs2) {
  29717. serializationObject.uvs2 = this.uvs2;
  29718. }
  29719. if (this.uvs3) {
  29720. serializationObject.uvs3 = this.uvs3;
  29721. }
  29722. if (this.uvs4) {
  29723. serializationObject.uvs4 = this.uvs4;
  29724. }
  29725. if (this.uvs5) {
  29726. serializationObject.uvs5 = this.uvs5;
  29727. }
  29728. if (this.uvs6) {
  29729. serializationObject.uvs6 = this.uvs6;
  29730. }
  29731. if (this.colors) {
  29732. serializationObject.colors = this.colors;
  29733. }
  29734. if (this.matricesIndices) {
  29735. serializationObject.matricesIndices = this.matricesIndices;
  29736. serializationObject.matricesIndices._isExpanded = true;
  29737. }
  29738. if (this.matricesWeights) {
  29739. serializationObject.matricesWeights = this.matricesWeights;
  29740. }
  29741. if (this.matricesIndicesExtra) {
  29742. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29743. serializationObject.matricesIndicesExtra._isExpanded = true;
  29744. }
  29745. if (this.matricesWeightsExtra) {
  29746. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29747. }
  29748. serializationObject.indices = this.indices;
  29749. return serializationObject;
  29750. };
  29751. // Statics
  29752. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  29753. return VertexData._ExtractFrom(mesh, copyWhenShared);
  29754. };
  29755. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  29756. return VertexData._ExtractFrom(geometry, copyWhenShared);
  29757. };
  29758. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  29759. var result = new VertexData();
  29760. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29761. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  29762. }
  29763. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29764. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  29765. }
  29766. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29767. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  29768. }
  29769. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29770. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  29771. }
  29772. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29773. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  29774. }
  29775. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29776. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  29777. }
  29778. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29779. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  29780. }
  29781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29782. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  29783. }
  29784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29785. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  29786. }
  29787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29788. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  29789. }
  29790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29791. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  29792. }
  29793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29794. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  29795. }
  29796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29797. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  29798. }
  29799. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29800. return result;
  29801. };
  29802. VertexData.CreateRibbon = function (options) {
  29803. var pathArray = options.pathArray;
  29804. var closeArray = options.closeArray || false;
  29805. var closePath = options.closePath || false;
  29806. var invertUV = options.invertUV || false;
  29807. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29808. var offset = options.offset || defaultOffset;
  29809. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29811. var positions = [];
  29812. var indices = [];
  29813. var normals = [];
  29814. var uvs = [];
  29815. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29816. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29817. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29818. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29819. var minlg; // minimal length among all paths from pathArray
  29820. var lg = []; // array of path lengths : nb of vertex per path
  29821. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29822. var p; // path iterator
  29823. var i; // point iterator
  29824. var j; // point iterator
  29825. // if single path in pathArray
  29826. if (pathArray.length < 2) {
  29827. var ar1 = [];
  29828. var ar2 = [];
  29829. for (i = 0; i < pathArray[0].length - offset; i++) {
  29830. ar1.push(pathArray[0][i]);
  29831. ar2.push(pathArray[0][i + offset]);
  29832. }
  29833. pathArray = [ar1, ar2];
  29834. }
  29835. // positions and horizontal distances (u)
  29836. var idc = 0;
  29837. var closePathCorr = (closePath) ? 1 : 0;
  29838. var path;
  29839. var l;
  29840. minlg = pathArray[0].length;
  29841. var vectlg;
  29842. var dist;
  29843. for (p = 0; p < pathArray.length; p++) {
  29844. uTotalDistance[p] = 0;
  29845. us[p] = [0];
  29846. path = pathArray[p];
  29847. l = path.length;
  29848. minlg = (minlg < l) ? minlg : l;
  29849. j = 0;
  29850. while (j < l) {
  29851. positions.push(path[j].x, path[j].y, path[j].z);
  29852. if (j > 0) {
  29853. vectlg = path[j].subtract(path[j - 1]).length();
  29854. dist = vectlg + uTotalDistance[p];
  29855. us[p].push(dist);
  29856. uTotalDistance[p] = dist;
  29857. }
  29858. j++;
  29859. }
  29860. if (closePath) {
  29861. j--;
  29862. positions.push(path[0].x, path[0].y, path[0].z);
  29863. vectlg = path[j].subtract(path[0]).length();
  29864. dist = vectlg + uTotalDistance[p];
  29865. us[p].push(dist);
  29866. uTotalDistance[p] = dist;
  29867. }
  29868. lg[p] = l + closePathCorr;
  29869. idx[p] = idc;
  29870. idc += (l + closePathCorr);
  29871. }
  29872. // vertical distances (v)
  29873. var path1;
  29874. var path2;
  29875. var vertex1;
  29876. var vertex2;
  29877. for (i = 0; i < minlg + closePathCorr; i++) {
  29878. vTotalDistance[i] = 0;
  29879. vs[i] = [0];
  29880. for (p = 0; p < pathArray.length - 1; p++) {
  29881. path1 = pathArray[p];
  29882. path2 = pathArray[p + 1];
  29883. if (i === minlg) {
  29884. vertex1 = path1[0];
  29885. vertex2 = path2[0];
  29886. }
  29887. else {
  29888. vertex1 = path1[i];
  29889. vertex2 = path2[i];
  29890. }
  29891. vectlg = vertex2.subtract(vertex1).length();
  29892. dist = vectlg + vTotalDistance[i];
  29893. vs[i].push(dist);
  29894. vTotalDistance[i] = dist;
  29895. }
  29896. if (closeArray) {
  29897. path1 = pathArray[p];
  29898. path2 = pathArray[0];
  29899. if (i === minlg) {
  29900. vertex2 = path2[0];
  29901. }
  29902. vectlg = vertex2.subtract(vertex1).length();
  29903. dist = vectlg + vTotalDistance[i];
  29904. vTotalDistance[i] = dist;
  29905. }
  29906. }
  29907. // uvs
  29908. var u;
  29909. var v;
  29910. for (p = 0; p < pathArray.length; p++) {
  29911. for (i = 0; i < minlg + closePathCorr; i++) {
  29912. u = us[p][i] / uTotalDistance[p];
  29913. v = vs[i][p] / vTotalDistance[i];
  29914. if (invertUV) {
  29915. uvs.push(v, u);
  29916. }
  29917. else {
  29918. uvs.push(u, v);
  29919. }
  29920. }
  29921. }
  29922. // indices
  29923. p = 0; // path index
  29924. var pi = 0; // positions array index
  29925. var l1 = lg[p] - 1; // path1 length
  29926. var l2 = lg[p + 1] - 1; // path2 length
  29927. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29928. var shft = idx[1] - idx[0]; // shift
  29929. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29930. while (pi <= min && p < path1nb) {
  29931. // 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
  29932. indices.push(pi, pi + shft, pi + 1);
  29933. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29934. pi += 1;
  29935. if (pi === min) {
  29936. p++;
  29937. if (p === lg.length - 1) {
  29938. shft = idx[0] - idx[p];
  29939. l1 = lg[p] - 1;
  29940. l2 = lg[0] - 1;
  29941. }
  29942. else {
  29943. shft = idx[p + 1] - idx[p];
  29944. l1 = lg[p] - 1;
  29945. l2 = lg[p + 1] - 1;
  29946. }
  29947. pi = idx[p];
  29948. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29949. }
  29950. }
  29951. // normals
  29952. VertexData.ComputeNormals(positions, indices, normals);
  29953. if (closePath) {
  29954. var indexFirst = 0;
  29955. var indexLast = 0;
  29956. for (p = 0; p < pathArray.length; p++) {
  29957. indexFirst = idx[p] * 3;
  29958. if (p + 1 < pathArray.length) {
  29959. indexLast = (idx[p + 1] - 1) * 3;
  29960. }
  29961. else {
  29962. indexLast = normals.length - 3;
  29963. }
  29964. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29965. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29966. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29967. normals[indexLast] = normals[indexFirst];
  29968. normals[indexLast + 1] = normals[indexFirst + 1];
  29969. normals[indexLast + 2] = normals[indexFirst + 2];
  29970. }
  29971. }
  29972. // sides
  29973. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29974. // Result
  29975. var vertexData = new VertexData();
  29976. vertexData.indices = indices;
  29977. vertexData.positions = positions;
  29978. vertexData.normals = normals;
  29979. vertexData.uvs = uvs;
  29980. if (closePath) {
  29981. vertexData._idx = idx;
  29982. }
  29983. return vertexData;
  29984. };
  29985. VertexData.CreateBox = function (options) {
  29986. var normalsSource = [
  29987. new BABYLON.Vector3(0, 0, 1),
  29988. new BABYLON.Vector3(0, 0, -1),
  29989. new BABYLON.Vector3(1, 0, 0),
  29990. new BABYLON.Vector3(-1, 0, 0),
  29991. new BABYLON.Vector3(0, 1, 0),
  29992. new BABYLON.Vector3(0, -1, 0)
  29993. ];
  29994. var indices = [];
  29995. var positions = [];
  29996. var normals = [];
  29997. var uvs = [];
  29998. var width = options.width || options.size || 1;
  29999. var height = options.height || options.size || 1;
  30000. var depth = options.depth || options.size || 1;
  30001. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30002. var faceUV = options.faceUV || new Array(6);
  30003. var faceColors = options.faceColors;
  30004. var colors = [];
  30005. // default face colors and UV if undefined
  30006. for (var f = 0; f < 6; f++) {
  30007. if (faceUV[f] === undefined) {
  30008. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30009. }
  30010. if (faceColors && faceColors[f] === undefined) {
  30011. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30012. }
  30013. }
  30014. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30015. // Create each face in turn.
  30016. for (var index = 0; index < normalsSource.length; index++) {
  30017. var normal = normalsSource[index];
  30018. // Get two vectors perpendicular to the face normal and to each other.
  30019. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30020. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30021. // Six indices (two triangles) per face.
  30022. var verticesLength = positions.length / 3;
  30023. indices.push(verticesLength);
  30024. indices.push(verticesLength + 1);
  30025. indices.push(verticesLength + 2);
  30026. indices.push(verticesLength);
  30027. indices.push(verticesLength + 2);
  30028. indices.push(verticesLength + 3);
  30029. // Four vertices per face.
  30030. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30031. positions.push(vertex.x, vertex.y, vertex.z);
  30032. normals.push(normal.x, normal.y, normal.z);
  30033. uvs.push(faceUV[index].z, faceUV[index].w);
  30034. if (faceColors) {
  30035. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30036. }
  30037. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30038. positions.push(vertex.x, vertex.y, vertex.z);
  30039. normals.push(normal.x, normal.y, normal.z);
  30040. uvs.push(faceUV[index].x, faceUV[index].w);
  30041. if (faceColors) {
  30042. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30043. }
  30044. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30045. positions.push(vertex.x, vertex.y, vertex.z);
  30046. normals.push(normal.x, normal.y, normal.z);
  30047. uvs.push(faceUV[index].x, faceUV[index].y);
  30048. if (faceColors) {
  30049. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30050. }
  30051. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30052. positions.push(vertex.x, vertex.y, vertex.z);
  30053. normals.push(normal.x, normal.y, normal.z);
  30054. uvs.push(faceUV[index].z, faceUV[index].y);
  30055. if (faceColors) {
  30056. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30057. }
  30058. }
  30059. // sides
  30060. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30061. // Result
  30062. var vertexData = new VertexData();
  30063. vertexData.indices = indices;
  30064. vertexData.positions = positions;
  30065. vertexData.normals = normals;
  30066. vertexData.uvs = uvs;
  30067. if (faceColors) {
  30068. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30069. vertexData.colors = totalColors;
  30070. }
  30071. return vertexData;
  30072. };
  30073. VertexData.CreateSphere = function (options) {
  30074. var segments = options.segments || 32;
  30075. var diameterX = options.diameterX || options.diameter || 1;
  30076. var diameterY = options.diameterY || options.diameter || 1;
  30077. var diameterZ = options.diameterZ || options.diameter || 1;
  30078. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30079. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30080. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30081. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30082. var totalZRotationSteps = 2 + segments;
  30083. var totalYRotationSteps = 2 * totalZRotationSteps;
  30084. var indices = [];
  30085. var positions = [];
  30086. var normals = [];
  30087. var uvs = [];
  30088. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30089. var normalizedZ = zRotationStep / totalZRotationSteps;
  30090. var angleZ = normalizedZ * Math.PI * slice;
  30091. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30092. var normalizedY = yRotationStep / totalYRotationSteps;
  30093. var angleY = normalizedY * Math.PI * 2 * arc;
  30094. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30095. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30096. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30097. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30098. var vertex = complete.multiply(radius);
  30099. var normal = complete.divide(radius).normalize();
  30100. positions.push(vertex.x, vertex.y, vertex.z);
  30101. normals.push(normal.x, normal.y, normal.z);
  30102. uvs.push(normalizedY, normalizedZ);
  30103. }
  30104. if (zRotationStep > 0) {
  30105. var verticesCount = positions.length / 3;
  30106. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30107. indices.push((firstIndex));
  30108. indices.push((firstIndex + 1));
  30109. indices.push(firstIndex + totalYRotationSteps + 1);
  30110. indices.push((firstIndex + totalYRotationSteps + 1));
  30111. indices.push((firstIndex + 1));
  30112. indices.push((firstIndex + totalYRotationSteps + 2));
  30113. }
  30114. }
  30115. }
  30116. // Sides
  30117. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30118. // Result
  30119. var vertexData = new VertexData();
  30120. vertexData.indices = indices;
  30121. vertexData.positions = positions;
  30122. vertexData.normals = normals;
  30123. vertexData.uvs = uvs;
  30124. return vertexData;
  30125. };
  30126. // Cylinder and cone
  30127. VertexData.CreateCylinder = function (options) {
  30128. var height = options.height || 2;
  30129. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30130. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30131. var tessellation = options.tessellation || 24;
  30132. var subdivisions = options.subdivisions || 1;
  30133. var hasRings = options.hasRings;
  30134. var enclose = options.enclose;
  30135. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30136. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30137. var faceUV = options.faceUV || new Array(3);
  30138. var faceColors = options.faceColors;
  30139. // default face colors and UV if undefined
  30140. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30141. var ringNb = (hasRings) ? subdivisions : 1;
  30142. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30143. var f;
  30144. for (f = 0; f < surfaceNb; f++) {
  30145. if (faceColors && faceColors[f] === undefined) {
  30146. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30147. }
  30148. }
  30149. for (f = 0; f < surfaceNb; f++) {
  30150. if (faceUV && faceUV[f] === undefined) {
  30151. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30152. }
  30153. }
  30154. var indices = [];
  30155. var positions = [];
  30156. var normals = [];
  30157. var uvs = [];
  30158. var colors = [];
  30159. var angle_step = Math.PI * 2 * arc / tessellation;
  30160. var angle;
  30161. var h;
  30162. var radius;
  30163. var tan = (diameterBottom - diameterTop) / 2 / height;
  30164. var ringVertex = BABYLON.Vector3.Zero();
  30165. var ringNormal = BABYLON.Vector3.Zero();
  30166. var ringFirstVertex = BABYLON.Vector3.Zero();
  30167. var ringFirstNormal = BABYLON.Vector3.Zero();
  30168. var quadNormal = BABYLON.Vector3.Zero();
  30169. var Y = BABYLON.Axis.Y;
  30170. // positions, normals, uvs
  30171. var i;
  30172. var j;
  30173. var r;
  30174. var ringIdx = 1;
  30175. var s = 1; // surface index
  30176. var cs = 0;
  30177. var v = 0;
  30178. for (i = 0; i <= subdivisions; i++) {
  30179. h = i / subdivisions;
  30180. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30181. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30182. for (r = 0; r < ringIdx; r++) {
  30183. if (hasRings) {
  30184. s += r;
  30185. }
  30186. if (enclose) {
  30187. s += 2 * r;
  30188. }
  30189. for (j = 0; j <= tessellation; j++) {
  30190. angle = j * angle_step;
  30191. // position
  30192. ringVertex.x = Math.cos(-angle) * radius;
  30193. ringVertex.y = -height / 2 + h * height;
  30194. ringVertex.z = Math.sin(-angle) * radius;
  30195. // normal
  30196. if (diameterTop === 0 && i === subdivisions) {
  30197. // if no top cap, reuse former normals
  30198. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30199. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30200. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30201. }
  30202. else {
  30203. ringNormal.x = ringVertex.x;
  30204. ringNormal.z = ringVertex.z;
  30205. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30206. ringNormal.normalize();
  30207. }
  30208. // keep first ring vertex values for enclose
  30209. if (j === 0) {
  30210. ringFirstVertex.copyFrom(ringVertex);
  30211. ringFirstNormal.copyFrom(ringNormal);
  30212. }
  30213. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30214. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30215. if (hasRings) {
  30216. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30217. }
  30218. else {
  30219. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30220. }
  30221. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30222. if (faceColors) {
  30223. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30224. }
  30225. }
  30226. // if enclose, add four vertices and their dedicated normals
  30227. if (arc !== 1 && enclose) {
  30228. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30229. positions.push(0, ringVertex.y, 0);
  30230. positions.push(0, ringVertex.y, 0);
  30231. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30232. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30233. quadNormal.normalize();
  30234. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30235. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30236. quadNormal.normalize();
  30237. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30238. if (hasRings) {
  30239. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30240. }
  30241. else {
  30242. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30243. }
  30244. uvs.push(faceUV[s + 1].x, v);
  30245. uvs.push(faceUV[s + 1].z, v);
  30246. if (hasRings) {
  30247. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30248. }
  30249. else {
  30250. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30251. }
  30252. uvs.push(faceUV[s + 2].x, v);
  30253. uvs.push(faceUV[s + 2].z, v);
  30254. if (faceColors) {
  30255. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30256. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30257. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30258. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30259. }
  30260. }
  30261. if (cs !== s) {
  30262. cs = s;
  30263. }
  30264. }
  30265. }
  30266. // indices
  30267. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30268. var s;
  30269. i = 0;
  30270. for (s = 0; s < subdivisions; s++) {
  30271. for (j = 0; j < tessellation; j++) {
  30272. var i0 = i * (e + 1) + j;
  30273. var i1 = (i + 1) * (e + 1) + j;
  30274. var i2 = i * (e + 1) + (j + 1);
  30275. var i3 = (i + 1) * (e + 1) + (j + 1);
  30276. indices.push(i0, i1, i2);
  30277. indices.push(i3, i2, i1);
  30278. }
  30279. if (arc !== 1 && enclose) {
  30280. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30281. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30282. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30283. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30284. }
  30285. i = (hasRings) ? (i + 2) : (i + 1);
  30286. }
  30287. // Caps
  30288. var createCylinderCap = function (isTop) {
  30289. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30290. if (radius === 0) {
  30291. return;
  30292. }
  30293. // Cap positions, normals & uvs
  30294. var angle;
  30295. var circleVector;
  30296. var i;
  30297. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30298. var c;
  30299. if (faceColors) {
  30300. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30301. }
  30302. // cap center
  30303. var vbase = positions.length / 3;
  30304. var offset = isTop ? height / 2 : -height / 2;
  30305. var center = new BABYLON.Vector3(0, offset, 0);
  30306. positions.push(center.x, center.y, center.z);
  30307. normals.push(0, isTop ? 1 : -1, 0);
  30308. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30309. if (faceColors) {
  30310. colors.push(c.r, c.g, c.b, c.a);
  30311. }
  30312. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30313. for (i = 0; i <= tessellation; i++) {
  30314. angle = Math.PI * 2 * i * arc / tessellation;
  30315. var cos = Math.cos(-angle);
  30316. var sin = Math.sin(-angle);
  30317. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30318. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30319. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30320. normals.push(0, isTop ? 1 : -1, 0);
  30321. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30322. if (faceColors) {
  30323. colors.push(c.r, c.g, c.b, c.a);
  30324. }
  30325. }
  30326. // Cap indices
  30327. for (i = 0; i < tessellation; i++) {
  30328. if (!isTop) {
  30329. indices.push(vbase);
  30330. indices.push(vbase + (i + 1));
  30331. indices.push(vbase + (i + 2));
  30332. }
  30333. else {
  30334. indices.push(vbase);
  30335. indices.push(vbase + (i + 2));
  30336. indices.push(vbase + (i + 1));
  30337. }
  30338. }
  30339. };
  30340. // add caps to geometry
  30341. createCylinderCap(false);
  30342. createCylinderCap(true);
  30343. // Sides
  30344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30345. var vertexData = new VertexData();
  30346. vertexData.indices = indices;
  30347. vertexData.positions = positions;
  30348. vertexData.normals = normals;
  30349. vertexData.uvs = uvs;
  30350. if (faceColors) {
  30351. vertexData.colors = colors;
  30352. }
  30353. return vertexData;
  30354. };
  30355. VertexData.CreateTorus = function (options) {
  30356. var indices = [];
  30357. var positions = [];
  30358. var normals = [];
  30359. var uvs = [];
  30360. var diameter = options.diameter || 1;
  30361. var thickness = options.thickness || 0.5;
  30362. var tessellation = options.tessellation || 16;
  30363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30364. var stride = tessellation + 1;
  30365. for (var i = 0; i <= tessellation; i++) {
  30366. var u = i / tessellation;
  30367. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30368. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30369. for (var j = 0; j <= tessellation; j++) {
  30370. var v = 1 - j / tessellation;
  30371. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30372. var dx = Math.cos(innerAngle);
  30373. var dy = Math.sin(innerAngle);
  30374. // Create a vertex.
  30375. var normal = new BABYLON.Vector3(dx, dy, 0);
  30376. var position = normal.scale(thickness / 2);
  30377. var textureCoordinate = new BABYLON.Vector2(u, v);
  30378. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30379. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30380. positions.push(position.x, position.y, position.z);
  30381. normals.push(normal.x, normal.y, normal.z);
  30382. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30383. // And create indices for two triangles.
  30384. var nextI = (i + 1) % stride;
  30385. var nextJ = (j + 1) % stride;
  30386. indices.push(i * stride + j);
  30387. indices.push(i * stride + nextJ);
  30388. indices.push(nextI * stride + j);
  30389. indices.push(i * stride + nextJ);
  30390. indices.push(nextI * stride + nextJ);
  30391. indices.push(nextI * stride + j);
  30392. }
  30393. }
  30394. // Sides
  30395. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30396. // Result
  30397. var vertexData = new VertexData();
  30398. vertexData.indices = indices;
  30399. vertexData.positions = positions;
  30400. vertexData.normals = normals;
  30401. vertexData.uvs = uvs;
  30402. return vertexData;
  30403. };
  30404. VertexData.CreateLineSystem = function (options) {
  30405. var indices = [];
  30406. var positions = [];
  30407. var lines = options.lines;
  30408. var idx = 0;
  30409. for (var l = 0; l < lines.length; l++) {
  30410. var points = lines[l];
  30411. for (var index = 0; index < points.length; index++) {
  30412. positions.push(points[index].x, points[index].y, points[index].z);
  30413. if (index > 0) {
  30414. indices.push(idx - 1);
  30415. indices.push(idx);
  30416. }
  30417. idx++;
  30418. }
  30419. }
  30420. var vertexData = new VertexData();
  30421. vertexData.indices = indices;
  30422. vertexData.positions = positions;
  30423. return vertexData;
  30424. };
  30425. VertexData.CreateDashedLines = function (options) {
  30426. var dashSize = options.dashSize || 3;
  30427. var gapSize = options.gapSize || 1;
  30428. var dashNb = options.dashNb || 200;
  30429. var points = options.points;
  30430. var positions = new Array();
  30431. var indices = new Array();
  30432. var curvect = BABYLON.Vector3.Zero();
  30433. var lg = 0;
  30434. var nb = 0;
  30435. var shft = 0;
  30436. var dashshft = 0;
  30437. var curshft = 0;
  30438. var idx = 0;
  30439. var i = 0;
  30440. for (i = 0; i < points.length - 1; i++) {
  30441. points[i + 1].subtractToRef(points[i], curvect);
  30442. lg += curvect.length();
  30443. }
  30444. shft = lg / dashNb;
  30445. dashshft = dashSize * shft / (dashSize + gapSize);
  30446. for (i = 0; i < points.length - 1; i++) {
  30447. points[i + 1].subtractToRef(points[i], curvect);
  30448. nb = Math.floor(curvect.length() / shft);
  30449. curvect.normalize();
  30450. for (var j = 0; j < nb; j++) {
  30451. curshft = shft * j;
  30452. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30453. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30454. indices.push(idx, idx + 1);
  30455. idx += 2;
  30456. }
  30457. }
  30458. // Result
  30459. var vertexData = new VertexData();
  30460. vertexData.positions = positions;
  30461. vertexData.indices = indices;
  30462. return vertexData;
  30463. };
  30464. VertexData.CreateGround = function (options) {
  30465. var indices = [];
  30466. var positions = [];
  30467. var normals = [];
  30468. var uvs = [];
  30469. var row, col;
  30470. var width = options.width || 1;
  30471. var height = options.height || 1;
  30472. var subdivisions = options.subdivisions || 1;
  30473. for (row = 0; row <= subdivisions; row++) {
  30474. for (col = 0; col <= subdivisions; col++) {
  30475. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  30476. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30477. positions.push(position.x, position.y, position.z);
  30478. normals.push(normal.x, normal.y, normal.z);
  30479. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  30480. }
  30481. }
  30482. for (row = 0; row < subdivisions; row++) {
  30483. for (col = 0; col < subdivisions; col++) {
  30484. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30485. indices.push(col + 1 + row * (subdivisions + 1));
  30486. indices.push(col + row * (subdivisions + 1));
  30487. indices.push(col + (row + 1) * (subdivisions + 1));
  30488. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  30489. indices.push(col + row * (subdivisions + 1));
  30490. }
  30491. }
  30492. // Result
  30493. var vertexData = new VertexData();
  30494. vertexData.indices = indices;
  30495. vertexData.positions = positions;
  30496. vertexData.normals = normals;
  30497. vertexData.uvs = uvs;
  30498. return vertexData;
  30499. };
  30500. VertexData.CreateTiledGround = function (options) {
  30501. var xmin = options.xmin || -1.0;
  30502. var zmin = options.zmin || -1.0;
  30503. var xmax = options.xmax || 1.0;
  30504. var zmax = options.zmax || 1.0;
  30505. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30506. var precision = options.precision || { w: 1, h: 1 };
  30507. var indices = [];
  30508. var positions = [];
  30509. var normals = [];
  30510. var uvs = [];
  30511. var row, col, tileRow, tileCol;
  30512. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30513. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30514. precision.w = (precision.w < 1) ? 1 : precision.w;
  30515. precision.h = (precision.h < 1) ? 1 : precision.h;
  30516. var tileSize = {
  30517. 'w': (xmax - xmin) / subdivisions.w,
  30518. 'h': (zmax - zmin) / subdivisions.h
  30519. };
  30520. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30521. // Indices
  30522. var base = positions.length / 3;
  30523. var rowLength = precision.w + 1;
  30524. for (row = 0; row < precision.h; row++) {
  30525. for (col = 0; col < precision.w; col++) {
  30526. var square = [
  30527. base + col + row * rowLength,
  30528. base + (col + 1) + row * rowLength,
  30529. base + (col + 1) + (row + 1) * rowLength,
  30530. base + col + (row + 1) * rowLength
  30531. ];
  30532. indices.push(square[1]);
  30533. indices.push(square[2]);
  30534. indices.push(square[3]);
  30535. indices.push(square[0]);
  30536. indices.push(square[1]);
  30537. indices.push(square[3]);
  30538. }
  30539. }
  30540. // Position, normals and uvs
  30541. var position = BABYLON.Vector3.Zero();
  30542. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30543. for (row = 0; row <= precision.h; row++) {
  30544. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30545. for (col = 0; col <= precision.w; col++) {
  30546. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30547. position.y = 0;
  30548. positions.push(position.x, position.y, position.z);
  30549. normals.push(normal.x, normal.y, normal.z);
  30550. uvs.push(col / precision.w, row / precision.h);
  30551. }
  30552. }
  30553. }
  30554. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30555. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30556. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30557. }
  30558. }
  30559. // Result
  30560. var vertexData = new VertexData();
  30561. vertexData.indices = indices;
  30562. vertexData.positions = positions;
  30563. vertexData.normals = normals;
  30564. vertexData.uvs = uvs;
  30565. return vertexData;
  30566. };
  30567. VertexData.CreateGroundFromHeightMap = function (options) {
  30568. var indices = [];
  30569. var positions = [];
  30570. var normals = [];
  30571. var uvs = [];
  30572. var row, col;
  30573. // Vertices
  30574. for (row = 0; row <= options.subdivisions; row++) {
  30575. for (col = 0; col <= options.subdivisions; col++) {
  30576. 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));
  30577. // Compute height
  30578. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30579. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30580. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30581. var r = options.buffer[pos] / 255.0;
  30582. var g = options.buffer[pos + 1] / 255.0;
  30583. var b = options.buffer[pos + 2] / 255.0;
  30584. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30585. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30586. // Add vertex
  30587. positions.push(position.x, position.y, position.z);
  30588. normals.push(0, 0, 0);
  30589. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30590. }
  30591. }
  30592. // Indices
  30593. for (row = 0; row < options.subdivisions; row++) {
  30594. for (col = 0; col < options.subdivisions; col++) {
  30595. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30596. indices.push(col + 1 + row * (options.subdivisions + 1));
  30597. indices.push(col + row * (options.subdivisions + 1));
  30598. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30599. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30600. indices.push(col + row * (options.subdivisions + 1));
  30601. }
  30602. }
  30603. // Normals
  30604. VertexData.ComputeNormals(positions, indices, normals);
  30605. // Result
  30606. var vertexData = new VertexData();
  30607. vertexData.indices = indices;
  30608. vertexData.positions = positions;
  30609. vertexData.normals = normals;
  30610. vertexData.uvs = uvs;
  30611. return vertexData;
  30612. };
  30613. VertexData.CreatePlane = function (options) {
  30614. var indices = [];
  30615. var positions = [];
  30616. var normals = [];
  30617. var uvs = [];
  30618. var width = options.width || options.size || 1;
  30619. var height = options.height || options.size || 1;
  30620. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30621. // Vertices
  30622. var halfWidth = width / 2.0;
  30623. var halfHeight = height / 2.0;
  30624. positions.push(-halfWidth, -halfHeight, 0);
  30625. normals.push(0, 0, -1.0);
  30626. uvs.push(0.0, 0.0);
  30627. positions.push(halfWidth, -halfHeight, 0);
  30628. normals.push(0, 0, -1.0);
  30629. uvs.push(1.0, 0.0);
  30630. positions.push(halfWidth, halfHeight, 0);
  30631. normals.push(0, 0, -1.0);
  30632. uvs.push(1.0, 1.0);
  30633. positions.push(-halfWidth, halfHeight, 0);
  30634. normals.push(0, 0, -1.0);
  30635. uvs.push(0.0, 1.0);
  30636. // Indices
  30637. indices.push(0);
  30638. indices.push(1);
  30639. indices.push(2);
  30640. indices.push(0);
  30641. indices.push(2);
  30642. indices.push(3);
  30643. // Sides
  30644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30645. // Result
  30646. var vertexData = new VertexData();
  30647. vertexData.indices = indices;
  30648. vertexData.positions = positions;
  30649. vertexData.normals = normals;
  30650. vertexData.uvs = uvs;
  30651. return vertexData;
  30652. };
  30653. VertexData.CreateDisc = function (options) {
  30654. var positions = [];
  30655. var indices = [];
  30656. var normals = [];
  30657. var uvs = [];
  30658. var radius = options.radius || 0.5;
  30659. var tessellation = options.tessellation || 64;
  30660. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30662. // positions and uvs
  30663. positions.push(0, 0, 0); // disc center first
  30664. uvs.push(0.5, 0.5);
  30665. var theta = Math.PI * 2 * arc;
  30666. var step = theta / tessellation;
  30667. for (var a = 0; a < theta; a += step) {
  30668. var x = Math.cos(a);
  30669. var y = Math.sin(a);
  30670. var u = (x + 1) / 2;
  30671. var v = (1 - y) / 2;
  30672. positions.push(radius * x, radius * y, 0);
  30673. uvs.push(u, v);
  30674. }
  30675. if (arc === 1) {
  30676. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30677. uvs.push(uvs[2], uvs[3]);
  30678. }
  30679. //indices
  30680. var vertexNb = positions.length / 3;
  30681. for (var i = 1; i < vertexNb - 1; i++) {
  30682. indices.push(i + 1, 0, i);
  30683. }
  30684. // result
  30685. VertexData.ComputeNormals(positions, indices, normals);
  30686. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30687. var vertexData = new VertexData();
  30688. vertexData.indices = indices;
  30689. vertexData.positions = positions;
  30690. vertexData.normals = normals;
  30691. vertexData.uvs = uvs;
  30692. return vertexData;
  30693. };
  30694. VertexData.CreateIcoSphere = function (options) {
  30695. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30696. var radius = options.radius || 1;
  30697. var flat = (options.flat === undefined) ? true : options.flat;
  30698. var subdivisions = options.subdivisions || 4;
  30699. var radiusX = options.radiusX || radius;
  30700. var radiusY = options.radiusY || radius;
  30701. var radiusZ = options.radiusZ || radius;
  30702. var t = (1 + Math.sqrt(5)) / 2;
  30703. // 12 vertex x,y,z
  30704. var ico_vertices = [
  30705. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30706. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30707. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30708. ];
  30709. // index of 3 vertex makes a face of icopshere
  30710. var ico_indices = [
  30711. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30712. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30713. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30714. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30715. ];
  30716. // vertex for uv have aliased position, not for UV
  30717. var vertices_unalias_id = [
  30718. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30719. // vertex alias
  30720. 0,
  30721. 2,
  30722. 3,
  30723. 3,
  30724. 3,
  30725. 4,
  30726. 7,
  30727. 8,
  30728. 9,
  30729. 9,
  30730. 10,
  30731. 11 // 23: B + 12
  30732. ];
  30733. // uv as integer step (not pixels !)
  30734. var ico_vertexuv = [
  30735. 5, 1, 3, 1, 6, 4, 0, 0,
  30736. 5, 3, 4, 2, 2, 2, 4, 0,
  30737. 2, 0, 1, 1, 6, 0, 6, 2,
  30738. // vertex alias (for same vertex on different faces)
  30739. 0, 4,
  30740. 3, 3,
  30741. 4, 4,
  30742. 3, 1,
  30743. 4, 2,
  30744. 4, 4,
  30745. 0, 2,
  30746. 1, 1,
  30747. 2, 2,
  30748. 3, 3,
  30749. 1, 3,
  30750. 2, 4 // 23: B + 12
  30751. ];
  30752. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30753. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30754. // First island of uv mapping
  30755. // v = 4h 3+ 2
  30756. // v = 3h 9+ 4
  30757. // v = 2h 9+ 5 B
  30758. // v = 1h 9 1 0
  30759. // v = 0h 3 8 7 A
  30760. // u = 0 1 2 3 4 5 6 *a
  30761. // Second island of uv mapping
  30762. // v = 4h 0+ B+ 4+
  30763. // v = 3h A+ 2+
  30764. // v = 2h 7+ 6 3+
  30765. // v = 1h 8+ 3+
  30766. // v = 0h
  30767. // u = 0 1 2 3 4 5 6 *a
  30768. // Face layout on texture UV mapping
  30769. // ============
  30770. // \ 4 /\ 16 / ======
  30771. // \ / \ / /\ 11 /
  30772. // \/ 7 \/ / \ /
  30773. // ======= / 10 \/
  30774. // /\ 17 /\ =======
  30775. // / \ / \ \ 15 /\
  30776. // / 8 \/ 12 \ \ / \
  30777. // ============ \/ 6 \
  30778. // \ 18 /\ ============
  30779. // \ / \ \ 5 /\ 0 /
  30780. // \/ 13 \ \ / \ /
  30781. // ======= \/ 1 \/
  30782. // =============
  30783. // /\ 19 /\ 2 /\
  30784. // / \ / \ / \
  30785. // / 14 \/ 9 \/ 3 \
  30786. // ===================
  30787. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30788. var ustep = 138 / 1024;
  30789. var vstep = 239 / 1024;
  30790. var uoffset = 60 / 1024;
  30791. var voffset = 26 / 1024;
  30792. // Second island should have margin, not to touch the first island
  30793. // avoid any borderline artefact in pixel rounding
  30794. var island_u_offset = -40 / 1024;
  30795. var island_v_offset = +20 / 1024;
  30796. // face is either island 0 or 1 :
  30797. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30798. var island = [
  30799. 0, 0, 0, 0, 1,
  30800. 0, 0, 1, 1, 0,
  30801. 0, 0, 1, 1, 0,
  30802. 0, 1, 1, 1, 0 // 15 - 19
  30803. ];
  30804. var indices = [];
  30805. var positions = [];
  30806. var normals = [];
  30807. var uvs = [];
  30808. var current_indice = 0;
  30809. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30810. var face_vertex_pos = new Array(3);
  30811. var face_vertex_uv = new Array(3);
  30812. var v012;
  30813. for (v012 = 0; v012 < 3; v012++) {
  30814. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30815. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30816. }
  30817. // create all with normals
  30818. for (var face = 0; face < 20; face++) {
  30819. // 3 vertex per face
  30820. for (v012 = 0; v012 < 3; v012++) {
  30821. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30822. var v_id = ico_indices[3 * face + v012];
  30823. // vertex have 3D position (x,y,z)
  30824. 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]);
  30825. // Normalize to get normal, then scale to radius
  30826. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30827. // uv Coordinates from vertex ID
  30828. 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);
  30829. }
  30830. // Subdivide the face (interpolate pos, norm, uv)
  30831. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30832. // - norm is linear interpolation of vertex corner normal
  30833. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30834. // - uv is linear interpolation
  30835. //
  30836. // Topology is as below for sub-divide by 2
  30837. // vertex shown as v0,v1,v2
  30838. // interp index is i1 to progress in range [v0,v1[
  30839. // interp index is i2 to progress in range [v0,v2[
  30840. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30841. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30842. //
  30843. //
  30844. // i2 v2
  30845. // ^ ^
  30846. // / / \
  30847. // / / \
  30848. // / / \
  30849. // / / (0,1) \
  30850. // / #---------\
  30851. // / / \ (0,0)'/ \
  30852. // / / \ / \
  30853. // / / \ / \
  30854. // / / (0,0) \ / (1,0) \
  30855. // / #---------#---------\
  30856. // v0 v1
  30857. //
  30858. // --------------------> i1
  30859. //
  30860. // interp of (i1,i2):
  30861. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30862. // along i1 : lerp(x0,x1, i1/(S-i2))
  30863. //
  30864. // centroid of triangle is needed to get help normal computation
  30865. // (c1,c2) are used for centroid location
  30866. var interp_vertex = function (i1, i2, c1, c2) {
  30867. // vertex is interpolated from
  30868. // - face_vertex_pos[0..2]
  30869. // - face_vertex_uv[0..2]
  30870. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30871. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30872. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30873. pos_interp.normalize();
  30874. var vertex_normal;
  30875. if (flat) {
  30876. // in flat mode, recalculate normal as face centroid normal
  30877. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30878. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30879. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30880. }
  30881. else {
  30882. // in smooth mode, recalculate normal from each single vertex position
  30883. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30884. }
  30885. // Vertex normal need correction due to X,Y,Z radius scaling
  30886. vertex_normal.x /= radiusX;
  30887. vertex_normal.y /= radiusY;
  30888. vertex_normal.z /= radiusZ;
  30889. vertex_normal.normalize();
  30890. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30891. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30892. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30893. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30894. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30895. uvs.push(uv_interp.x, uv_interp.y);
  30896. // push each vertex has member of a face
  30897. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30898. indices.push(current_indice);
  30899. current_indice++;
  30900. };
  30901. for (var i2 = 0; i2 < subdivisions; i2++) {
  30902. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30903. // face : (i1,i2) for /\ :
  30904. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30905. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30906. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30907. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30908. if (i1 + i2 + 1 < subdivisions) {
  30909. // face : (i1,i2)' for \/ :
  30910. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30911. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30912. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30913. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30914. }
  30915. }
  30916. }
  30917. }
  30918. // Sides
  30919. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30920. // Result
  30921. var vertexData = new VertexData();
  30922. vertexData.indices = indices;
  30923. vertexData.positions = positions;
  30924. vertexData.normals = normals;
  30925. vertexData.uvs = uvs;
  30926. return vertexData;
  30927. };
  30928. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30929. VertexData.CreatePolyhedron = function (options) {
  30930. // provided polyhedron types :
  30931. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30932. // 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)
  30933. var polyhedra = [];
  30934. 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]] };
  30935. 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]] };
  30936. polyhedra[2] = {
  30937. 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]],
  30938. 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]]
  30939. };
  30940. polyhedra[3] = {
  30941. 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]],
  30942. 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]]
  30943. };
  30944. polyhedra[4] = {
  30945. 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]],
  30946. 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]]
  30947. };
  30948. 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]] };
  30949. 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]] };
  30950. 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]] };
  30951. 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]] };
  30952. 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]] };
  30953. 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]] };
  30954. 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]] };
  30955. 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]] };
  30956. 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]] };
  30957. polyhedra[14] = {
  30958. 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]],
  30959. 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]]
  30960. };
  30961. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30962. var size = options.size;
  30963. var sizeX = options.sizeX || size || 1;
  30964. var sizeY = options.sizeY || size || 1;
  30965. var sizeZ = options.sizeZ || size || 1;
  30966. var data = options.custom || polyhedra[type];
  30967. var nbfaces = data.face.length;
  30968. var faceUV = options.faceUV || new Array(nbfaces);
  30969. var faceColors = options.faceColors;
  30970. var flat = (options.flat === undefined) ? true : options.flat;
  30971. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30972. var positions = [];
  30973. var indices = [];
  30974. var normals = [];
  30975. var uvs = [];
  30976. var colors = [];
  30977. var index = 0;
  30978. var faceIdx = 0; // face cursor in the array "indexes"
  30979. var indexes = [];
  30980. var i = 0;
  30981. var f = 0;
  30982. var u, v, ang, x, y, tmp;
  30983. // default face colors and UV if undefined
  30984. if (flat) {
  30985. for (f = 0; f < nbfaces; f++) {
  30986. if (faceColors && faceColors[f] === undefined) {
  30987. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30988. }
  30989. if (faceUV && faceUV[f] === undefined) {
  30990. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30991. }
  30992. }
  30993. }
  30994. if (!flat) {
  30995. for (i = 0; i < data.vertex.length; i++) {
  30996. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30997. uvs.push(0, 0);
  30998. }
  30999. for (f = 0; f < nbfaces; f++) {
  31000. for (i = 0; i < data.face[f].length - 2; i++) {
  31001. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31002. }
  31003. }
  31004. }
  31005. else {
  31006. for (f = 0; f < nbfaces; f++) {
  31007. var fl = data.face[f].length; // number of vertices of the current face
  31008. ang = 2 * Math.PI / fl;
  31009. x = 0.5 * Math.tan(ang / 2);
  31010. y = 0.5;
  31011. // positions, uvs, colors
  31012. for (i = 0; i < fl; i++) {
  31013. // positions
  31014. 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);
  31015. indexes.push(index);
  31016. index++;
  31017. // uvs
  31018. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31019. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31020. uvs.push(u, v);
  31021. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31022. y = x * Math.sin(ang) + y * Math.cos(ang);
  31023. x = tmp;
  31024. // colors
  31025. if (faceColors) {
  31026. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31027. }
  31028. }
  31029. // indices from indexes
  31030. for (i = 0; i < fl - 2; i++) {
  31031. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31032. }
  31033. faceIdx += fl;
  31034. }
  31035. }
  31036. VertexData.ComputeNormals(positions, indices, normals);
  31037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31038. var vertexData = new VertexData();
  31039. vertexData.positions = positions;
  31040. vertexData.indices = indices;
  31041. vertexData.normals = normals;
  31042. vertexData.uvs = uvs;
  31043. if (faceColors && flat) {
  31044. vertexData.colors = colors;
  31045. }
  31046. return vertexData;
  31047. };
  31048. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31049. VertexData.CreateTorusKnot = function (options) {
  31050. var indices = [];
  31051. var positions = [];
  31052. var normals = [];
  31053. var uvs = [];
  31054. var radius = options.radius || 2;
  31055. var tube = options.tube || 0.5;
  31056. var radialSegments = options.radialSegments || 32;
  31057. var tubularSegments = options.tubularSegments || 32;
  31058. var p = options.p || 2;
  31059. var q = options.q || 3;
  31060. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31061. // Helper
  31062. var getPos = function (angle) {
  31063. var cu = Math.cos(angle);
  31064. var su = Math.sin(angle);
  31065. var quOverP = q / p * angle;
  31066. var cs = Math.cos(quOverP);
  31067. var tx = radius * (2 + cs) * 0.5 * cu;
  31068. var ty = radius * (2 + cs) * su * 0.5;
  31069. var tz = radius * Math.sin(quOverP) * 0.5;
  31070. return new BABYLON.Vector3(tx, ty, tz);
  31071. };
  31072. // Vertices
  31073. var i;
  31074. var j;
  31075. for (i = 0; i <= radialSegments; i++) {
  31076. var modI = i % radialSegments;
  31077. var u = modI / radialSegments * 2 * p * Math.PI;
  31078. var p1 = getPos(u);
  31079. var p2 = getPos(u + 0.01);
  31080. var tang = p2.subtract(p1);
  31081. var n = p2.add(p1);
  31082. var bitan = BABYLON.Vector3.Cross(tang, n);
  31083. n = BABYLON.Vector3.Cross(bitan, tang);
  31084. bitan.normalize();
  31085. n.normalize();
  31086. for (j = 0; j < tubularSegments; j++) {
  31087. var modJ = j % tubularSegments;
  31088. var v = modJ / tubularSegments * 2 * Math.PI;
  31089. var cx = -tube * Math.cos(v);
  31090. var cy = tube * Math.sin(v);
  31091. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31092. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31093. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31094. uvs.push(i / radialSegments);
  31095. uvs.push(j / tubularSegments);
  31096. }
  31097. }
  31098. for (i = 0; i < radialSegments; i++) {
  31099. for (j = 0; j < tubularSegments; j++) {
  31100. var jNext = (j + 1) % tubularSegments;
  31101. var a = i * tubularSegments + j;
  31102. var b = (i + 1) * tubularSegments + j;
  31103. var c = (i + 1) * tubularSegments + jNext;
  31104. var d = i * tubularSegments + jNext;
  31105. indices.push(d);
  31106. indices.push(b);
  31107. indices.push(a);
  31108. indices.push(d);
  31109. indices.push(c);
  31110. indices.push(b);
  31111. }
  31112. }
  31113. // Normals
  31114. VertexData.ComputeNormals(positions, indices, normals);
  31115. // Sides
  31116. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31117. // Result
  31118. var vertexData = new VertexData();
  31119. vertexData.indices = indices;
  31120. vertexData.positions = positions;
  31121. vertexData.normals = normals;
  31122. vertexData.uvs = uvs;
  31123. return vertexData;
  31124. };
  31125. // Tools
  31126. /**
  31127. * @param {any} - positions (number[] or Float32Array)
  31128. * @param {any} - indices (number[] or Uint16Array)
  31129. * @param {any} - normals (number[] or Float32Array)
  31130. */
  31131. VertexData.ComputeNormals = function (positions, indices, normals) {
  31132. var index = 0;
  31133. var p1p2x = 0.0;
  31134. var p1p2y = 0.0;
  31135. var p1p2z = 0.0;
  31136. var p3p2x = 0.0;
  31137. var p3p2y = 0.0;
  31138. var p3p2z = 0.0;
  31139. var faceNormalx = 0.0;
  31140. var faceNormaly = 0.0;
  31141. var faceNormalz = 0.0;
  31142. var length = 0.0;
  31143. var i1 = 0;
  31144. var i2 = 0;
  31145. var i3 = 0;
  31146. for (index = 0; index < positions.length; index++) {
  31147. normals[index] = 0.0;
  31148. }
  31149. // indice triplet = 1 face
  31150. var nbFaces = indices.length / 3;
  31151. for (index = 0; index < nbFaces; index++) {
  31152. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31153. i2 = indices[index * 3 + 1];
  31154. i3 = indices[index * 3 + 2];
  31155. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31156. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31157. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31158. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31159. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31160. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31161. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31162. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31163. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31164. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31165. length = (length === 0) ? 1.0 : length;
  31166. faceNormalx /= length; // normalize this normal
  31167. faceNormaly /= length;
  31168. faceNormalz /= length;
  31169. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31170. normals[i1 * 3 + 1] += faceNormaly;
  31171. normals[i1 * 3 + 2] += faceNormalz;
  31172. normals[i2 * 3] += faceNormalx;
  31173. normals[i2 * 3 + 1] += faceNormaly;
  31174. normals[i2 * 3 + 2] += faceNormalz;
  31175. normals[i3 * 3] += faceNormalx;
  31176. normals[i3 * 3 + 1] += faceNormaly;
  31177. normals[i3 * 3 + 2] += faceNormalz;
  31178. }
  31179. // last normalization of each normal
  31180. for (index = 0; index < normals.length / 3; index++) {
  31181. faceNormalx = normals[index * 3];
  31182. faceNormaly = normals[index * 3 + 1];
  31183. faceNormalz = normals[index * 3 + 2];
  31184. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31185. length = (length === 0) ? 1.0 : length;
  31186. faceNormalx /= length;
  31187. faceNormaly /= length;
  31188. faceNormalz /= length;
  31189. normals[index * 3] = faceNormalx;
  31190. normals[index * 3 + 1] = faceNormaly;
  31191. normals[index * 3 + 2] = faceNormalz;
  31192. }
  31193. };
  31194. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31195. var li = indices.length;
  31196. var ln = normals.length;
  31197. var i;
  31198. var n;
  31199. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31200. switch (sideOrientation) {
  31201. case BABYLON.Mesh.FRONTSIDE:
  31202. // nothing changed
  31203. break;
  31204. case BABYLON.Mesh.BACKSIDE:
  31205. var tmp;
  31206. // indices
  31207. for (i = 0; i < li; i += 3) {
  31208. tmp = indices[i];
  31209. indices[i] = indices[i + 2];
  31210. indices[i + 2] = tmp;
  31211. }
  31212. // normals
  31213. for (n = 0; n < ln; n++) {
  31214. normals[n] = -normals[n];
  31215. }
  31216. break;
  31217. case BABYLON.Mesh.DOUBLESIDE:
  31218. // positions
  31219. var lp = positions.length;
  31220. var l = lp / 3;
  31221. for (var p = 0; p < lp; p++) {
  31222. positions[lp + p] = positions[p];
  31223. }
  31224. // indices
  31225. for (i = 0; i < li; i += 3) {
  31226. indices[i + li] = indices[i + 2] + l;
  31227. indices[i + 1 + li] = indices[i + 1] + l;
  31228. indices[i + 2 + li] = indices[i] + l;
  31229. }
  31230. // normals
  31231. for (n = 0; n < ln; n++) {
  31232. normals[ln + n] = -normals[n];
  31233. }
  31234. // uvs
  31235. var lu = uvs.length;
  31236. for (var u = 0; u < lu; u++) {
  31237. uvs[u + lu] = uvs[u];
  31238. }
  31239. break;
  31240. }
  31241. };
  31242. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31243. var vertexData = new VertexData();
  31244. // positions
  31245. var positions = parsedVertexData.positions;
  31246. if (positions) {
  31247. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31248. }
  31249. // normals
  31250. var normals = parsedVertexData.normals;
  31251. if (normals) {
  31252. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31253. }
  31254. // uvs
  31255. var uvs = parsedVertexData.uvs;
  31256. if (uvs) {
  31257. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31258. }
  31259. // uv2s
  31260. var uv2s = parsedVertexData.uv2s;
  31261. if (uv2s) {
  31262. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31263. }
  31264. // uv3s
  31265. var uv3s = parsedVertexData.uv3s;
  31266. if (uv3s) {
  31267. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31268. }
  31269. // uv4s
  31270. var uv4s = parsedVertexData.uv4s;
  31271. if (uv4s) {
  31272. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31273. }
  31274. // uv5s
  31275. var uv5s = parsedVertexData.uv5s;
  31276. if (uv5s) {
  31277. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31278. }
  31279. // uv6s
  31280. var uv6s = parsedVertexData.uv6s;
  31281. if (uv6s) {
  31282. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31283. }
  31284. // colors
  31285. var colors = parsedVertexData.colors;
  31286. if (colors) {
  31287. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31288. }
  31289. // matricesIndices
  31290. var matricesIndices = parsedVertexData.matricesIndices;
  31291. if (matricesIndices) {
  31292. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31293. }
  31294. // matricesWeights
  31295. var matricesWeights = parsedVertexData.matricesWeights;
  31296. if (matricesWeights) {
  31297. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31298. }
  31299. // indices
  31300. var indices = parsedVertexData.indices;
  31301. if (indices) {
  31302. vertexData.indices = indices;
  31303. }
  31304. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31305. };
  31306. return VertexData;
  31307. })();
  31308. BABYLON.VertexData = VertexData;
  31309. })(BABYLON || (BABYLON = {}));
  31310. var BABYLON;
  31311. (function (BABYLON) {
  31312. var Tags = (function () {
  31313. function Tags() {
  31314. }
  31315. Tags.EnableFor = function (obj) {
  31316. obj._tags = obj._tags || {};
  31317. obj.hasTags = function () {
  31318. return Tags.HasTags(obj);
  31319. };
  31320. obj.addTags = function (tagsString) {
  31321. return Tags.AddTagsTo(obj, tagsString);
  31322. };
  31323. obj.removeTags = function (tagsString) {
  31324. return Tags.RemoveTagsFrom(obj, tagsString);
  31325. };
  31326. obj.matchesTagsQuery = function (tagsQuery) {
  31327. return Tags.MatchesQuery(obj, tagsQuery);
  31328. };
  31329. };
  31330. Tags.DisableFor = function (obj) {
  31331. delete obj._tags;
  31332. delete obj.hasTags;
  31333. delete obj.addTags;
  31334. delete obj.removeTags;
  31335. delete obj.matchesTagsQuery;
  31336. };
  31337. Tags.HasTags = function (obj) {
  31338. if (!obj._tags) {
  31339. return false;
  31340. }
  31341. return !BABYLON.Tools.IsEmpty(obj._tags);
  31342. };
  31343. Tags.GetTags = function (obj, asString) {
  31344. if (asString === void 0) { asString = true; }
  31345. if (!obj._tags) {
  31346. return null;
  31347. }
  31348. if (asString) {
  31349. var tagsArray = [];
  31350. for (var tag in obj._tags) {
  31351. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31352. tagsArray.push(tag);
  31353. }
  31354. }
  31355. return tagsArray.join(" ");
  31356. }
  31357. else {
  31358. return obj._tags;
  31359. }
  31360. };
  31361. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31362. // a tag cannot start with '||', '&&', and '!'
  31363. // it cannot contain whitespaces
  31364. Tags.AddTagsTo = function (obj, tagsString) {
  31365. if (!tagsString) {
  31366. return;
  31367. }
  31368. if (typeof tagsString !== "string") {
  31369. return;
  31370. }
  31371. var tags = tagsString.split(" ");
  31372. for (var t in tags) {
  31373. Tags._AddTagTo(obj, tags[t]);
  31374. }
  31375. };
  31376. Tags._AddTagTo = function (obj, tag) {
  31377. tag = tag.trim();
  31378. if (tag === "" || tag === "true" || tag === "false") {
  31379. return;
  31380. }
  31381. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  31382. return;
  31383. }
  31384. Tags.EnableFor(obj);
  31385. obj._tags[tag] = true;
  31386. };
  31387. Tags.RemoveTagsFrom = function (obj, tagsString) {
  31388. if (!Tags.HasTags(obj)) {
  31389. return;
  31390. }
  31391. var tags = tagsString.split(" ");
  31392. for (var t in tags) {
  31393. Tags._RemoveTagFrom(obj, tags[t]);
  31394. }
  31395. };
  31396. Tags._RemoveTagFrom = function (obj, tag) {
  31397. delete obj._tags[tag];
  31398. };
  31399. Tags.MatchesQuery = function (obj, tagsQuery) {
  31400. if (tagsQuery === undefined) {
  31401. return true;
  31402. }
  31403. if (tagsQuery === "") {
  31404. return Tags.HasTags(obj);
  31405. }
  31406. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  31407. };
  31408. return Tags;
  31409. })();
  31410. BABYLON.Tags = Tags;
  31411. })(BABYLON || (BABYLON = {}));
  31412. var BABYLON;
  31413. (function (BABYLON) {
  31414. var Internals;
  31415. (function (Internals) {
  31416. var AndOrNotEvaluator = (function () {
  31417. function AndOrNotEvaluator() {
  31418. }
  31419. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  31420. if (!query.match(/\([^\(\)]*\)/g)) {
  31421. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  31422. }
  31423. else {
  31424. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  31425. // remove parenthesis
  31426. r = r.slice(1, r.length - 1);
  31427. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  31428. });
  31429. }
  31430. if (query === "true") {
  31431. return true;
  31432. }
  31433. if (query === "false") {
  31434. return false;
  31435. }
  31436. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  31437. };
  31438. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  31439. evaluateCallback = evaluateCallback || (function (r) {
  31440. return r === "true" ? true : false;
  31441. });
  31442. var result;
  31443. var or = parenthesisContent.split("||");
  31444. for (var i in or) {
  31445. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  31446. var and = ori.split("&&");
  31447. if (and.length > 1) {
  31448. for (var j = 0; j < and.length; ++j) {
  31449. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  31450. if (andj !== "true" && andj !== "false") {
  31451. if (andj[0] === "!") {
  31452. result = !evaluateCallback(andj.substring(1));
  31453. }
  31454. else {
  31455. result = evaluateCallback(andj);
  31456. }
  31457. }
  31458. else {
  31459. result = andj === "true" ? true : false;
  31460. }
  31461. if (!result) {
  31462. ori = "false";
  31463. break;
  31464. }
  31465. }
  31466. }
  31467. if (result || ori === "true") {
  31468. result = true;
  31469. break;
  31470. }
  31471. // result equals false (or undefined)
  31472. if (ori !== "true" && ori !== "false") {
  31473. if (ori[0] === "!") {
  31474. result = !evaluateCallback(ori.substring(1));
  31475. }
  31476. else {
  31477. result = evaluateCallback(ori);
  31478. }
  31479. }
  31480. else {
  31481. result = ori === "true" ? true : false;
  31482. }
  31483. }
  31484. // the whole parenthesis scope is replaced by 'true' or 'false'
  31485. return result ? "true" : "false";
  31486. };
  31487. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  31488. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  31489. // remove whitespaces
  31490. r = r.replace(/[\s]/g, function () { return ""; });
  31491. return r.length % 2 ? "!" : "";
  31492. });
  31493. booleanString = booleanString.trim();
  31494. if (booleanString === "!true") {
  31495. booleanString = "false";
  31496. }
  31497. else if (booleanString === "!false") {
  31498. booleanString = "true";
  31499. }
  31500. return booleanString;
  31501. };
  31502. return AndOrNotEvaluator;
  31503. })();
  31504. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  31505. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31506. })(BABYLON || (BABYLON = {}));
  31507. var BABYLON;
  31508. (function (BABYLON) {
  31509. var PostProcessRenderPass = (function () {
  31510. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  31511. this._enabled = true;
  31512. this._refCount = 0;
  31513. this._name = name;
  31514. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  31515. this.setRenderList(renderList);
  31516. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  31517. this._renderTexture.onAfterRenderObservable.add(afterRender);
  31518. this._scene = scene;
  31519. this._renderList = renderList;
  31520. }
  31521. // private
  31522. PostProcessRenderPass.prototype._incRefCount = function () {
  31523. if (this._refCount === 0) {
  31524. this._scene.customRenderTargets.push(this._renderTexture);
  31525. }
  31526. return ++this._refCount;
  31527. };
  31528. PostProcessRenderPass.prototype._decRefCount = function () {
  31529. this._refCount--;
  31530. if (this._refCount <= 0) {
  31531. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  31532. }
  31533. return this._refCount;
  31534. };
  31535. PostProcessRenderPass.prototype._update = function () {
  31536. this.setRenderList(this._renderList);
  31537. };
  31538. // public
  31539. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  31540. this._renderTexture.renderList = renderList;
  31541. };
  31542. PostProcessRenderPass.prototype.getRenderTexture = function () {
  31543. return this._renderTexture;
  31544. };
  31545. return PostProcessRenderPass;
  31546. })();
  31547. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  31548. })(BABYLON || (BABYLON = {}));
  31549. var BABYLON;
  31550. (function (BABYLON) {
  31551. var PostProcessRenderEffect = (function () {
  31552. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  31553. this._engine = engine;
  31554. this._name = name;
  31555. this._singleInstance = singleInstance || true;
  31556. this._getPostProcess = getPostProcess;
  31557. this._cameras = [];
  31558. this._indicesForCamera = [];
  31559. this._postProcesses = {};
  31560. this._renderPasses = {};
  31561. this._renderEffectAsPasses = {};
  31562. }
  31563. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  31564. get: function () {
  31565. for (var index in this._postProcesses) {
  31566. if (!this._postProcesses[index].isSupported) {
  31567. return false;
  31568. }
  31569. }
  31570. return true;
  31571. },
  31572. enumerable: true,
  31573. configurable: true
  31574. });
  31575. PostProcessRenderEffect.prototype._update = function () {
  31576. for (var renderPassName in this._renderPasses) {
  31577. this._renderPasses[renderPassName]._update();
  31578. }
  31579. };
  31580. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  31581. this._renderPasses[renderPass._name] = renderPass;
  31582. this._linkParameters();
  31583. };
  31584. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  31585. delete this._renderPasses[renderPass._name];
  31586. this._linkParameters();
  31587. };
  31588. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  31589. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  31590. this._linkParameters();
  31591. };
  31592. PostProcessRenderEffect.prototype.getPass = function (passName) {
  31593. for (var renderPassName in this._renderPasses) {
  31594. if (renderPassName === passName) {
  31595. return this._renderPasses[passName];
  31596. }
  31597. }
  31598. };
  31599. PostProcessRenderEffect.prototype.emptyPasses = function () {
  31600. this._renderPasses = {};
  31601. this._linkParameters();
  31602. };
  31603. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  31604. var cameraKey;
  31605. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31606. for (var i = 0; i < _cam.length; i++) {
  31607. var camera = _cam[i];
  31608. var cameraName = camera.name;
  31609. if (this._singleInstance) {
  31610. cameraKey = 0;
  31611. }
  31612. else {
  31613. cameraKey = cameraName;
  31614. }
  31615. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  31616. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  31617. if (!this._indicesForCamera[cameraName]) {
  31618. this._indicesForCamera[cameraName] = [];
  31619. }
  31620. this._indicesForCamera[cameraName].push(index);
  31621. if (this._cameras.indexOf(camera) === -1) {
  31622. this._cameras[cameraName] = camera;
  31623. }
  31624. for (var passName in this._renderPasses) {
  31625. this._renderPasses[passName]._incRefCount();
  31626. }
  31627. }
  31628. this._linkParameters();
  31629. };
  31630. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  31631. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31632. for (var i = 0; i < _cam.length; i++) {
  31633. var camera = _cam[i];
  31634. var cameraName = camera.name;
  31635. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31636. var index = this._cameras.indexOf(cameraName);
  31637. this._indicesForCamera.splice(index, 1);
  31638. this._cameras.splice(index, 1);
  31639. for (var passName in this._renderPasses) {
  31640. this._renderPasses[passName]._decRefCount();
  31641. }
  31642. }
  31643. };
  31644. PostProcessRenderEffect.prototype._enable = function (cameras) {
  31645. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31646. for (var i = 0; i < _cam.length; i++) {
  31647. var camera = _cam[i];
  31648. var cameraName = camera.name;
  31649. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  31650. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  31651. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  31652. }
  31653. }
  31654. for (var passName in this._renderPasses) {
  31655. this._renderPasses[passName]._incRefCount();
  31656. }
  31657. }
  31658. };
  31659. PostProcessRenderEffect.prototype._disable = function (cameras) {
  31660. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31661. for (var i = 0; i < _cam.length; i++) {
  31662. var camera = _cam[i];
  31663. var cameraName = camera.Name;
  31664. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  31665. for (var passName in this._renderPasses) {
  31666. this._renderPasses[passName]._decRefCount();
  31667. }
  31668. }
  31669. };
  31670. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  31671. if (this._singleInstance) {
  31672. return this._postProcesses[0];
  31673. }
  31674. else {
  31675. return this._postProcesses[camera.name];
  31676. }
  31677. };
  31678. PostProcessRenderEffect.prototype._linkParameters = function () {
  31679. var _this = this;
  31680. for (var index in this._postProcesses) {
  31681. if (this.applyParameters) {
  31682. this.applyParameters(this._postProcesses[index]);
  31683. }
  31684. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  31685. _this._linkTextures(effect);
  31686. });
  31687. }
  31688. };
  31689. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  31690. for (var renderPassName in this._renderPasses) {
  31691. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  31692. }
  31693. for (var renderEffectName in this._renderEffectAsPasses) {
  31694. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  31695. }
  31696. };
  31697. return PostProcessRenderEffect;
  31698. })();
  31699. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  31700. })(BABYLON || (BABYLON = {}));
  31701. var BABYLON;
  31702. (function (BABYLON) {
  31703. var PostProcessRenderPipeline = (function () {
  31704. function PostProcessRenderPipeline(engine, name) {
  31705. this._engine = engine;
  31706. this._name = name;
  31707. this._renderEffects = {};
  31708. this._renderEffectsForIsolatedPass = {};
  31709. this._cameras = [];
  31710. }
  31711. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  31712. get: function () {
  31713. for (var renderEffectName in this._renderEffects) {
  31714. if (!this._renderEffects[renderEffectName].isSupported) {
  31715. return false;
  31716. }
  31717. }
  31718. return true;
  31719. },
  31720. enumerable: true,
  31721. configurable: true
  31722. });
  31723. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  31724. this._renderEffects[renderEffect._name] = renderEffect;
  31725. };
  31726. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  31727. var renderEffects = this._renderEffects[renderEffectName];
  31728. if (!renderEffects) {
  31729. return;
  31730. }
  31731. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31732. };
  31733. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  31734. var renderEffects = this._renderEffects[renderEffectName];
  31735. if (!renderEffects) {
  31736. return;
  31737. }
  31738. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  31739. };
  31740. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  31741. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31742. var indicesToDelete = [];
  31743. var i;
  31744. for (i = 0; i < _cam.length; i++) {
  31745. var camera = _cam[i];
  31746. var cameraName = camera.name;
  31747. if (this._cameras.indexOf(camera) === -1) {
  31748. this._cameras[cameraName] = camera;
  31749. }
  31750. else if (unique) {
  31751. indicesToDelete.push(i);
  31752. }
  31753. }
  31754. for (i = 0; i < indicesToDelete.length; i++) {
  31755. cameras.splice(indicesToDelete[i], 1);
  31756. }
  31757. for (var renderEffectName in this._renderEffects) {
  31758. this._renderEffects[renderEffectName]._attachCameras(_cam);
  31759. }
  31760. };
  31761. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  31762. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31763. for (var renderEffectName in this._renderEffects) {
  31764. this._renderEffects[renderEffectName]._detachCameras(_cam);
  31765. }
  31766. for (var i = 0; i < _cam.length; i++) {
  31767. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  31768. }
  31769. };
  31770. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  31771. var _this = this;
  31772. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31773. var pass = null;
  31774. var renderEffectName;
  31775. for (renderEffectName in this._renderEffects) {
  31776. pass = this._renderEffects[renderEffectName].getPass(passName);
  31777. if (pass != null) {
  31778. break;
  31779. }
  31780. }
  31781. if (pass === null) {
  31782. return;
  31783. }
  31784. for (renderEffectName in this._renderEffects) {
  31785. this._renderEffects[renderEffectName]._disable(_cam);
  31786. }
  31787. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  31788. for (var i = 0; i < _cam.length; i++) {
  31789. var camera = _cam[i];
  31790. var cameraName = camera.name;
  31791. 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); });
  31792. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  31793. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  31794. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  31795. }
  31796. };
  31797. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  31798. var _this = this;
  31799. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  31800. for (var i = 0; i < _cam.length; i++) {
  31801. var camera = _cam[i];
  31802. var cameraName = camera.name;
  31803. 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); });
  31804. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  31805. }
  31806. for (var renderEffectName in this._renderEffects) {
  31807. this._renderEffects[renderEffectName]._enable(_cam);
  31808. }
  31809. };
  31810. PostProcessRenderPipeline.prototype._update = function () {
  31811. for (var renderEffectName in this._renderEffects) {
  31812. this._renderEffects[renderEffectName]._update();
  31813. }
  31814. for (var i = 0; i < this._cameras.length; i++) {
  31815. var cameraName = this._cameras[i].name;
  31816. if (this._renderEffectsForIsolatedPass[cameraName]) {
  31817. this._renderEffectsForIsolatedPass[cameraName]._update();
  31818. }
  31819. }
  31820. };
  31821. PostProcessRenderPipeline.prototype.dispose = function () {
  31822. // Must be implemented by children
  31823. };
  31824. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  31825. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  31826. return PostProcessRenderPipeline;
  31827. })();
  31828. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  31829. })(BABYLON || (BABYLON = {}));
  31830. var BABYLON;
  31831. (function (BABYLON) {
  31832. var PostProcessRenderPipelineManager = (function () {
  31833. function PostProcessRenderPipelineManager() {
  31834. this._renderPipelines = {};
  31835. }
  31836. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  31837. this._renderPipelines[renderPipeline._name] = renderPipeline;
  31838. };
  31839. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  31840. var renderPipeline = this._renderPipelines[renderPipelineName];
  31841. if (!renderPipeline) {
  31842. return;
  31843. }
  31844. renderPipeline._attachCameras(cameras, unique);
  31845. };
  31846. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  31847. var renderPipeline = this._renderPipelines[renderPipelineName];
  31848. if (!renderPipeline) {
  31849. return;
  31850. }
  31851. renderPipeline._detachCameras(cameras);
  31852. };
  31853. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31854. var renderPipeline = this._renderPipelines[renderPipelineName];
  31855. if (!renderPipeline) {
  31856. return;
  31857. }
  31858. renderPipeline._enableEffect(renderEffectName, cameras);
  31859. };
  31860. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  31861. var renderPipeline = this._renderPipelines[renderPipelineName];
  31862. if (!renderPipeline) {
  31863. return;
  31864. }
  31865. renderPipeline._disableEffect(renderEffectName, cameras);
  31866. };
  31867. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  31868. var renderPipeline = this._renderPipelines[renderPipelineName];
  31869. if (!renderPipeline) {
  31870. return;
  31871. }
  31872. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  31873. };
  31874. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  31875. var renderPipeline = this._renderPipelines[renderPipelineName];
  31876. if (!renderPipeline) {
  31877. return;
  31878. }
  31879. renderPipeline._disableDisplayOnlyPass(cameras);
  31880. };
  31881. PostProcessRenderPipelineManager.prototype.update = function () {
  31882. for (var renderPipelineName in this._renderPipelines) {
  31883. var pipeline = this._renderPipelines[renderPipelineName];
  31884. if (!pipeline.isSupported) {
  31885. pipeline.dispose();
  31886. delete this._renderPipelines[renderPipelineName];
  31887. }
  31888. else {
  31889. pipeline._update();
  31890. }
  31891. }
  31892. };
  31893. return PostProcessRenderPipelineManager;
  31894. })();
  31895. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  31896. })(BABYLON || (BABYLON = {}));
  31897. var BABYLON;
  31898. (function (BABYLON) {
  31899. var BoundingBoxRenderer = (function () {
  31900. function BoundingBoxRenderer(scene) {
  31901. this.frontColor = new BABYLON.Color3(1, 1, 1);
  31902. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  31903. this.showBackLines = true;
  31904. this.renderList = new BABYLON.SmartArray(32);
  31905. this._vertexBuffers = {};
  31906. this._scene = scene;
  31907. }
  31908. BoundingBoxRenderer.prototype._prepareRessources = function () {
  31909. if (this._colorShader) {
  31910. return;
  31911. }
  31912. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  31913. attributes: [BABYLON.VertexBuffer.PositionKind],
  31914. uniforms: ["worldViewProjection", "color"]
  31915. });
  31916. var engine = this._scene.getEngine();
  31917. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  31918. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  31919. 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]);
  31920. };
  31921. BoundingBoxRenderer.prototype.reset = function () {
  31922. this.renderList.reset();
  31923. };
  31924. BoundingBoxRenderer.prototype.render = function () {
  31925. if (this.renderList.length === 0) {
  31926. return;
  31927. }
  31928. this._prepareRessources();
  31929. if (!this._colorShader.isReady()) {
  31930. return;
  31931. }
  31932. var engine = this._scene.getEngine();
  31933. engine.setDepthWrite(false);
  31934. this._colorShader._preBind();
  31935. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  31936. var boundingBox = this.renderList.data[boundingBoxIndex];
  31937. var min = boundingBox.minimum;
  31938. var max = boundingBox.maximum;
  31939. var diff = max.subtract(min);
  31940. var median = min.add(diff.scale(0.5));
  31941. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  31942. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  31943. .multiply(boundingBox.getWorldMatrix());
  31944. // VBOs
  31945. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  31946. if (this.showBackLines) {
  31947. // Back
  31948. engine.setDepthFunctionToGreaterOrEqual();
  31949. this._scene.resetCachedMaterial();
  31950. this._colorShader.setColor4("color", this.backColor.toColor4());
  31951. this._colorShader.bind(worldMatrix);
  31952. // Draw order
  31953. engine.draw(false, 0, 24);
  31954. }
  31955. // Front
  31956. engine.setDepthFunctionToLess();
  31957. this._scene.resetCachedMaterial();
  31958. this._colorShader.setColor4("color", this.frontColor.toColor4());
  31959. this._colorShader.bind(worldMatrix);
  31960. // Draw order
  31961. engine.draw(false, 0, 24);
  31962. }
  31963. this._colorShader.unbind();
  31964. engine.setDepthFunctionToLessOrEqual();
  31965. engine.setDepthWrite(true);
  31966. };
  31967. BoundingBoxRenderer.prototype.dispose = function () {
  31968. if (!this._colorShader) {
  31969. return;
  31970. }
  31971. this._colorShader.dispose();
  31972. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31973. if (buffer) {
  31974. buffer.dispose();
  31975. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31976. }
  31977. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31978. };
  31979. return BoundingBoxRenderer;
  31980. })();
  31981. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  31982. })(BABYLON || (BABYLON = {}));
  31983. var BABYLON;
  31984. (function (BABYLON) {
  31985. var Condition = (function () {
  31986. function Condition(actionManager) {
  31987. this._actionManager = actionManager;
  31988. }
  31989. Condition.prototype.isValid = function () {
  31990. return true;
  31991. };
  31992. Condition.prototype._getProperty = function (propertyPath) {
  31993. return this._actionManager._getProperty(propertyPath);
  31994. };
  31995. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  31996. return this._actionManager._getEffectiveTarget(target, propertyPath);
  31997. };
  31998. Condition.prototype.serialize = function () {
  31999. };
  32000. Condition.prototype._serialize = function (serializedCondition) {
  32001. return {
  32002. type: 2,
  32003. children: [],
  32004. name: serializedCondition.name,
  32005. properties: serializedCondition.properties
  32006. };
  32007. };
  32008. return Condition;
  32009. })();
  32010. BABYLON.Condition = Condition;
  32011. var ValueCondition = (function (_super) {
  32012. __extends(ValueCondition, _super);
  32013. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32014. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32015. _super.call(this, actionManager);
  32016. this.propertyPath = propertyPath;
  32017. this.value = value;
  32018. this.operator = operator;
  32019. this._target = target;
  32020. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32021. this._property = this._getProperty(this.propertyPath);
  32022. }
  32023. Object.defineProperty(ValueCondition, "IsEqual", {
  32024. get: function () {
  32025. return ValueCondition._IsEqual;
  32026. },
  32027. enumerable: true,
  32028. configurable: true
  32029. });
  32030. Object.defineProperty(ValueCondition, "IsDifferent", {
  32031. get: function () {
  32032. return ValueCondition._IsDifferent;
  32033. },
  32034. enumerable: true,
  32035. configurable: true
  32036. });
  32037. Object.defineProperty(ValueCondition, "IsGreater", {
  32038. get: function () {
  32039. return ValueCondition._IsGreater;
  32040. },
  32041. enumerable: true,
  32042. configurable: true
  32043. });
  32044. Object.defineProperty(ValueCondition, "IsLesser", {
  32045. get: function () {
  32046. return ValueCondition._IsLesser;
  32047. },
  32048. enumerable: true,
  32049. configurable: true
  32050. });
  32051. // Methods
  32052. ValueCondition.prototype.isValid = function () {
  32053. switch (this.operator) {
  32054. case ValueCondition.IsGreater:
  32055. return this._effectiveTarget[this._property] > this.value;
  32056. case ValueCondition.IsLesser:
  32057. return this._effectiveTarget[this._property] < this.value;
  32058. case ValueCondition.IsEqual:
  32059. case ValueCondition.IsDifferent:
  32060. var check;
  32061. if (this.value.equals) {
  32062. check = this.value.equals(this._effectiveTarget[this._property]);
  32063. }
  32064. else {
  32065. check = this.value === this._effectiveTarget[this._property];
  32066. }
  32067. return this.operator === ValueCondition.IsEqual ? check : !check;
  32068. }
  32069. return false;
  32070. };
  32071. ValueCondition.prototype.serialize = function () {
  32072. return this._serialize({
  32073. name: "ValueCondition",
  32074. properties: [
  32075. BABYLON.Action._GetTargetProperty(this._target),
  32076. { name: "propertyPath", value: this.propertyPath },
  32077. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32078. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32079. ]
  32080. });
  32081. };
  32082. ValueCondition.GetOperatorName = function (operator) {
  32083. switch (operator) {
  32084. case ValueCondition._IsEqual: return "IsEqual";
  32085. case ValueCondition._IsDifferent: return "IsDifferent";
  32086. case ValueCondition._IsGreater: return "IsGreater";
  32087. case ValueCondition._IsLesser: return "IsLesser";
  32088. default: return "";
  32089. }
  32090. };
  32091. // Statics
  32092. ValueCondition._IsEqual = 0;
  32093. ValueCondition._IsDifferent = 1;
  32094. ValueCondition._IsGreater = 2;
  32095. ValueCondition._IsLesser = 3;
  32096. return ValueCondition;
  32097. })(Condition);
  32098. BABYLON.ValueCondition = ValueCondition;
  32099. var PredicateCondition = (function (_super) {
  32100. __extends(PredicateCondition, _super);
  32101. function PredicateCondition(actionManager, predicate) {
  32102. _super.call(this, actionManager);
  32103. this.predicate = predicate;
  32104. }
  32105. PredicateCondition.prototype.isValid = function () {
  32106. return this.predicate();
  32107. };
  32108. return PredicateCondition;
  32109. })(Condition);
  32110. BABYLON.PredicateCondition = PredicateCondition;
  32111. var StateCondition = (function (_super) {
  32112. __extends(StateCondition, _super);
  32113. function StateCondition(actionManager, target, value) {
  32114. _super.call(this, actionManager);
  32115. this.value = value;
  32116. this._target = target;
  32117. }
  32118. // Methods
  32119. StateCondition.prototype.isValid = function () {
  32120. return this._target.state === this.value;
  32121. };
  32122. StateCondition.prototype.serialize = function () {
  32123. return this._serialize({
  32124. name: "StateCondition",
  32125. properties: [
  32126. BABYLON.Action._GetTargetProperty(this._target),
  32127. { name: "value", value: this.value }
  32128. ]
  32129. });
  32130. };
  32131. return StateCondition;
  32132. })(Condition);
  32133. BABYLON.StateCondition = StateCondition;
  32134. })(BABYLON || (BABYLON = {}));
  32135. var BABYLON;
  32136. (function (BABYLON) {
  32137. var Action = (function () {
  32138. function Action(triggerOptions, condition) {
  32139. this.triggerOptions = triggerOptions;
  32140. if (triggerOptions.parameter) {
  32141. this.trigger = triggerOptions.trigger;
  32142. this._triggerParameter = triggerOptions.parameter;
  32143. }
  32144. else {
  32145. this.trigger = triggerOptions;
  32146. }
  32147. this._nextActiveAction = this;
  32148. this._condition = condition;
  32149. }
  32150. // Methods
  32151. Action.prototype._prepare = function () {
  32152. };
  32153. Action.prototype.getTriggerParameter = function () {
  32154. return this._triggerParameter;
  32155. };
  32156. Action.prototype._executeCurrent = function (evt) {
  32157. if (this._nextActiveAction._condition) {
  32158. var condition = this._nextActiveAction._condition;
  32159. var currentRenderId = this._actionManager.getScene().getRenderId();
  32160. // We cache the current evaluation for the current frame
  32161. if (condition._evaluationId === currentRenderId) {
  32162. if (!condition._currentResult) {
  32163. return;
  32164. }
  32165. }
  32166. else {
  32167. condition._evaluationId = currentRenderId;
  32168. if (!condition.isValid()) {
  32169. condition._currentResult = false;
  32170. return;
  32171. }
  32172. condition._currentResult = true;
  32173. }
  32174. }
  32175. this._nextActiveAction.execute(evt);
  32176. this.skipToNextActiveAction();
  32177. };
  32178. Action.prototype.execute = function (evt) {
  32179. };
  32180. Action.prototype.skipToNextActiveAction = function () {
  32181. if (this._nextActiveAction._child) {
  32182. if (!this._nextActiveAction._child._actionManager) {
  32183. this._nextActiveAction._child._actionManager = this._actionManager;
  32184. }
  32185. this._nextActiveAction = this._nextActiveAction._child;
  32186. }
  32187. else {
  32188. this._nextActiveAction = this;
  32189. }
  32190. };
  32191. Action.prototype.then = function (action) {
  32192. this._child = action;
  32193. action._actionManager = this._actionManager;
  32194. action._prepare();
  32195. return action;
  32196. };
  32197. Action.prototype._getProperty = function (propertyPath) {
  32198. return this._actionManager._getProperty(propertyPath);
  32199. };
  32200. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32201. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32202. };
  32203. Action.prototype.serialize = function (parent) {
  32204. };
  32205. // Called by BABYLON.Action objects in serialize(...). Internal use
  32206. Action.prototype._serialize = function (serializedAction, parent) {
  32207. var serializationObject = {
  32208. type: 1,
  32209. children: [],
  32210. name: serializedAction.name,
  32211. properties: serializedAction.properties || []
  32212. };
  32213. // Serialize child
  32214. if (this._child) {
  32215. this._child.serialize(serializationObject);
  32216. }
  32217. // Check if "this" has a condition
  32218. if (this._condition) {
  32219. var serializedCondition = this._condition.serialize();
  32220. serializedCondition.children.push(serializationObject);
  32221. if (parent) {
  32222. parent.children.push(serializedCondition);
  32223. }
  32224. return serializedCondition;
  32225. }
  32226. if (parent) {
  32227. parent.children.push(serializationObject);
  32228. }
  32229. return serializationObject;
  32230. };
  32231. Action._SerializeValueAsString = function (value) {
  32232. if (typeof value === "number") {
  32233. return value.toString();
  32234. }
  32235. if (typeof value === "boolean") {
  32236. return value ? "true" : "false";
  32237. }
  32238. if (value instanceof BABYLON.Vector2) {
  32239. return value.x + ", " + value.y;
  32240. }
  32241. if (value instanceof BABYLON.Vector3) {
  32242. return value.x + ", " + value.y + ", " + value.z;
  32243. }
  32244. if (value instanceof BABYLON.Color3) {
  32245. return value.r + ", " + value.g + ", " + value.b;
  32246. }
  32247. if (value instanceof BABYLON.Color4) {
  32248. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32249. }
  32250. return value; // string
  32251. };
  32252. Action._GetTargetProperty = function (target) {
  32253. return {
  32254. name: "target",
  32255. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32256. : target instanceof BABYLON.Light ? "LightProperties"
  32257. : target instanceof BABYLON.Camera ? "CameraProperties"
  32258. : "SceneProperties",
  32259. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32260. };
  32261. };
  32262. return Action;
  32263. })();
  32264. BABYLON.Action = Action;
  32265. })(BABYLON || (BABYLON = {}));
  32266. var BABYLON;
  32267. (function (BABYLON) {
  32268. /**
  32269. * ActionEvent is the event beint sent when an action is triggered.
  32270. */
  32271. var ActionEvent = (function () {
  32272. /**
  32273. * @constructor
  32274. * @param source The mesh or sprite that triggered the action.
  32275. * @param pointerX The X mouse cursor position at the time of the event
  32276. * @param pointerY The Y mouse cursor position at the time of the event
  32277. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32278. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32279. */
  32280. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32281. this.source = source;
  32282. this.pointerX = pointerX;
  32283. this.pointerY = pointerY;
  32284. this.meshUnderPointer = meshUnderPointer;
  32285. this.sourceEvent = sourceEvent;
  32286. this.additionalData = additionalData;
  32287. }
  32288. /**
  32289. * Helper function to auto-create an ActionEvent from a source mesh.
  32290. * @param source The source mesh that triggered the event
  32291. * @param evt {Event} The original (browser) event
  32292. */
  32293. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32294. var scene = source.getScene();
  32295. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32296. };
  32297. /**
  32298. * Helper function to auto-create an ActionEvent from a source mesh.
  32299. * @param source The source sprite that triggered the event
  32300. * @param scene Scene associated with the sprite
  32301. * @param evt {Event} The original (browser) event
  32302. */
  32303. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32304. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32305. };
  32306. /**
  32307. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32308. * @param scene the scene where the event occurred
  32309. * @param evt {Event} The original (browser) event
  32310. */
  32311. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32312. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32313. };
  32314. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32315. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32316. };
  32317. return ActionEvent;
  32318. })();
  32319. BABYLON.ActionEvent = ActionEvent;
  32320. /**
  32321. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32322. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32323. */
  32324. var ActionManager = (function () {
  32325. function ActionManager(scene) {
  32326. // Members
  32327. this.actions = new Array();
  32328. this._scene = scene;
  32329. scene._actionManagers.push(this);
  32330. }
  32331. Object.defineProperty(ActionManager, "NothingTrigger", {
  32332. get: function () {
  32333. return ActionManager._NothingTrigger;
  32334. },
  32335. enumerable: true,
  32336. configurable: true
  32337. });
  32338. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32339. get: function () {
  32340. return ActionManager._OnPickTrigger;
  32341. },
  32342. enumerable: true,
  32343. configurable: true
  32344. });
  32345. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32346. get: function () {
  32347. return ActionManager._OnLeftPickTrigger;
  32348. },
  32349. enumerable: true,
  32350. configurable: true
  32351. });
  32352. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32353. get: function () {
  32354. return ActionManager._OnRightPickTrigger;
  32355. },
  32356. enumerable: true,
  32357. configurable: true
  32358. });
  32359. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32360. get: function () {
  32361. return ActionManager._OnCenterPickTrigger;
  32362. },
  32363. enumerable: true,
  32364. configurable: true
  32365. });
  32366. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32367. get: function () {
  32368. return ActionManager._OnPickDownTrigger;
  32369. },
  32370. enumerable: true,
  32371. configurable: true
  32372. });
  32373. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  32374. get: function () {
  32375. return ActionManager._OnPickUpTrigger;
  32376. },
  32377. enumerable: true,
  32378. configurable: true
  32379. });
  32380. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  32381. /// This trigger will only be raised if you also declared a OnPickDown
  32382. get: function () {
  32383. return ActionManager._OnPickOutTrigger;
  32384. },
  32385. enumerable: true,
  32386. configurable: true
  32387. });
  32388. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  32389. get: function () {
  32390. return ActionManager._OnLongPressTrigger;
  32391. },
  32392. enumerable: true,
  32393. configurable: true
  32394. });
  32395. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  32396. get: function () {
  32397. return ActionManager._OnPointerOverTrigger;
  32398. },
  32399. enumerable: true,
  32400. configurable: true
  32401. });
  32402. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  32403. get: function () {
  32404. return ActionManager._OnPointerOutTrigger;
  32405. },
  32406. enumerable: true,
  32407. configurable: true
  32408. });
  32409. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  32410. get: function () {
  32411. return ActionManager._OnEveryFrameTrigger;
  32412. },
  32413. enumerable: true,
  32414. configurable: true
  32415. });
  32416. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  32417. get: function () {
  32418. return ActionManager._OnIntersectionEnterTrigger;
  32419. },
  32420. enumerable: true,
  32421. configurable: true
  32422. });
  32423. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  32424. get: function () {
  32425. return ActionManager._OnIntersectionExitTrigger;
  32426. },
  32427. enumerable: true,
  32428. configurable: true
  32429. });
  32430. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  32431. get: function () {
  32432. return ActionManager._OnKeyDownTrigger;
  32433. },
  32434. enumerable: true,
  32435. configurable: true
  32436. });
  32437. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  32438. get: function () {
  32439. return ActionManager._OnKeyUpTrigger;
  32440. },
  32441. enumerable: true,
  32442. configurable: true
  32443. });
  32444. // Methods
  32445. ActionManager.prototype.dispose = function () {
  32446. var index = this._scene._actionManagers.indexOf(this);
  32447. if (index > -1) {
  32448. this._scene._actionManagers.splice(index, 1);
  32449. }
  32450. };
  32451. ActionManager.prototype.getScene = function () {
  32452. return this._scene;
  32453. };
  32454. /**
  32455. * Does this action manager handles actions of any of the given triggers
  32456. * @param {number[]} triggers - the triggers to be tested
  32457. * @return {boolean} whether one (or more) of the triggers is handeled
  32458. */
  32459. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  32460. for (var index = 0; index < this.actions.length; index++) {
  32461. var action = this.actions[index];
  32462. if (triggers.indexOf(action.trigger) > -1) {
  32463. return true;
  32464. }
  32465. }
  32466. return false;
  32467. };
  32468. /**
  32469. * Does this action manager handles actions of a given trigger
  32470. * @param {number} trigger - the trigger to be tested
  32471. * @return {boolean} whether the trigger is handeled
  32472. */
  32473. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  32474. for (var index = 0; index < this.actions.length; index++) {
  32475. var action = this.actions[index];
  32476. if (action.trigger === trigger) {
  32477. return true;
  32478. }
  32479. }
  32480. return false;
  32481. };
  32482. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  32483. /**
  32484. * Does this action manager has pointer triggers
  32485. * @return {boolean} whether or not it has pointer triggers
  32486. */
  32487. get: function () {
  32488. for (var index = 0; index < this.actions.length; index++) {
  32489. var action = this.actions[index];
  32490. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  32491. return true;
  32492. }
  32493. }
  32494. return false;
  32495. },
  32496. enumerable: true,
  32497. configurable: true
  32498. });
  32499. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  32500. /**
  32501. * Does this action manager has pick triggers
  32502. * @return {boolean} whether or not it has pick triggers
  32503. */
  32504. get: function () {
  32505. for (var index = 0; index < this.actions.length; index++) {
  32506. var action = this.actions[index];
  32507. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  32508. return true;
  32509. }
  32510. }
  32511. return false;
  32512. },
  32513. enumerable: true,
  32514. configurable: true
  32515. });
  32516. /**
  32517. * Registers an action to this action manager
  32518. * @param {BABYLON.Action} action - the action to be registered
  32519. * @return {BABYLON.Action} the action amended (prepared) after registration
  32520. */
  32521. ActionManager.prototype.registerAction = function (action) {
  32522. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  32523. if (this.getScene().actionManager !== this) {
  32524. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  32525. return null;
  32526. }
  32527. }
  32528. this.actions.push(action);
  32529. action._actionManager = this;
  32530. action._prepare();
  32531. return action;
  32532. };
  32533. /**
  32534. * Process a specific trigger
  32535. * @param {number} trigger - the trigger to process
  32536. * @param evt {BABYLON.ActionEvent} the event details to be processed
  32537. */
  32538. ActionManager.prototype.processTrigger = function (trigger, evt) {
  32539. for (var index = 0; index < this.actions.length; index++) {
  32540. var action = this.actions[index];
  32541. if (action.trigger === trigger) {
  32542. if (trigger === ActionManager.OnKeyUpTrigger
  32543. || trigger === ActionManager.OnKeyDownTrigger) {
  32544. var parameter = action.getTriggerParameter();
  32545. if (parameter) {
  32546. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  32547. var actualkey = String.fromCharCode(unicode).toLowerCase();
  32548. if (actualkey !== parameter.toLowerCase()) {
  32549. continue;
  32550. }
  32551. }
  32552. }
  32553. action._executeCurrent(evt);
  32554. }
  32555. }
  32556. };
  32557. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  32558. var properties = propertyPath.split(".");
  32559. for (var index = 0; index < properties.length - 1; index++) {
  32560. target = target[properties[index]];
  32561. }
  32562. return target;
  32563. };
  32564. ActionManager.prototype._getProperty = function (propertyPath) {
  32565. var properties = propertyPath.split(".");
  32566. return properties[properties.length - 1];
  32567. };
  32568. ActionManager.prototype.serialize = function (name) {
  32569. var root = {
  32570. children: [],
  32571. name: name,
  32572. type: 3,
  32573. properties: [] // Empty for root but required
  32574. };
  32575. for (var i = 0; i < this.actions.length; i++) {
  32576. var triggerObject = {
  32577. type: 0,
  32578. children: [],
  32579. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  32580. properties: []
  32581. };
  32582. var triggerOptions = this.actions[i].triggerOptions;
  32583. if (triggerOptions && typeof triggerOptions !== "number") {
  32584. if (triggerOptions.parameter instanceof BABYLON.Node) {
  32585. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  32586. }
  32587. else {
  32588. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  32589. }
  32590. }
  32591. // Serialize child action, recursively
  32592. this.actions[i].serialize(triggerObject);
  32593. // Add serialized trigger
  32594. root.children.push(triggerObject);
  32595. }
  32596. return root;
  32597. };
  32598. ActionManager.Parse = function (parsedActions, object, scene) {
  32599. var actionManager = new BABYLON.ActionManager(scene);
  32600. if (object === null)
  32601. scene.actionManager = actionManager;
  32602. else
  32603. object.actionManager = actionManager;
  32604. // instanciate a new object
  32605. var instanciate = function (name, params) {
  32606. var newInstance = Object.create(BABYLON[name].prototype);
  32607. newInstance.constructor.apply(newInstance, params);
  32608. return newInstance;
  32609. };
  32610. var parseParameter = function (name, value, target, propertyPath) {
  32611. if (propertyPath === null) {
  32612. // String, boolean or float
  32613. var floatValue = parseFloat(value);
  32614. if (value === "true" || value === "false")
  32615. return value === "true";
  32616. else
  32617. return isNaN(floatValue) ? value : floatValue;
  32618. }
  32619. var effectiveTarget = propertyPath.split(".");
  32620. var values = value.split(",");
  32621. // Get effective Target
  32622. for (var i = 0; i < effectiveTarget.length; i++) {
  32623. target = target[effectiveTarget[i]];
  32624. }
  32625. // Return appropriate value with its type
  32626. if (typeof (target) === "boolean")
  32627. return values[0] === "true";
  32628. if (typeof (target) === "string")
  32629. return values[0];
  32630. // Parameters with multiple values such as Vector3 etc.
  32631. var split = new Array();
  32632. for (var i = 0; i < values.length; i++)
  32633. split.push(parseFloat(values[i]));
  32634. if (target instanceof BABYLON.Vector3)
  32635. return BABYLON.Vector3.FromArray(split);
  32636. if (target instanceof BABYLON.Vector4)
  32637. return BABYLON.Vector4.FromArray(split);
  32638. if (target instanceof BABYLON.Color3)
  32639. return BABYLON.Color3.FromArray(split);
  32640. if (target instanceof BABYLON.Color4)
  32641. return BABYLON.Color4.FromArray(split);
  32642. return parseFloat(values[0]);
  32643. };
  32644. // traverse graph per trigger
  32645. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  32646. if (combineArray === void 0) { combineArray = null; }
  32647. if (parsedAction.detached)
  32648. return;
  32649. var parameters = new Array();
  32650. var target = null;
  32651. var propertyPath = null;
  32652. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  32653. // Parameters
  32654. if (parsedAction.type === 2)
  32655. parameters.push(actionManager);
  32656. else
  32657. parameters.push(trigger);
  32658. if (combine) {
  32659. var actions = new Array();
  32660. for (var j = 0; j < parsedAction.combine.length; j++) {
  32661. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  32662. }
  32663. parameters.push(actions);
  32664. }
  32665. else {
  32666. for (var i = 0; i < parsedAction.properties.length; i++) {
  32667. var value = parsedAction.properties[i].value;
  32668. var name = parsedAction.properties[i].name;
  32669. var targetType = parsedAction.properties[i].targetType;
  32670. if (name === "target")
  32671. if (targetType !== null && targetType === "SceneProperties")
  32672. value = target = scene;
  32673. else
  32674. value = target = scene.getNodeByName(value);
  32675. else if (name === "parent")
  32676. value = scene.getNodeByName(value);
  32677. else if (name === "sound")
  32678. value = scene.getSoundByName(value);
  32679. else if (name !== "propertyPath") {
  32680. if (parsedAction.type === 2 && name === "operator")
  32681. value = BABYLON.ValueCondition[value];
  32682. else
  32683. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  32684. }
  32685. else {
  32686. propertyPath = value;
  32687. }
  32688. parameters.push(value);
  32689. }
  32690. }
  32691. if (combineArray === null) {
  32692. parameters.push(condition);
  32693. }
  32694. else {
  32695. parameters.push(null);
  32696. }
  32697. // If interpolate value action
  32698. if (parsedAction.name === "InterpolateValueAction") {
  32699. var param = parameters[parameters.length - 2];
  32700. parameters[parameters.length - 1] = param;
  32701. parameters[parameters.length - 2] = condition;
  32702. }
  32703. // Action or condition(s) and not CombineAction
  32704. var newAction = instanciate(parsedAction.name, parameters);
  32705. if (newAction instanceof BABYLON.Condition && condition !== null) {
  32706. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  32707. if (action)
  32708. action.then(nothing);
  32709. else
  32710. actionManager.registerAction(nothing);
  32711. action = nothing;
  32712. }
  32713. if (combineArray === null) {
  32714. if (newAction instanceof BABYLON.Condition) {
  32715. condition = newAction;
  32716. newAction = action;
  32717. }
  32718. else {
  32719. condition = null;
  32720. if (action)
  32721. action.then(newAction);
  32722. else
  32723. actionManager.registerAction(newAction);
  32724. }
  32725. }
  32726. else {
  32727. combineArray.push(newAction);
  32728. }
  32729. for (var i = 0; i < parsedAction.children.length; i++)
  32730. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  32731. };
  32732. // triggers
  32733. for (var i = 0; i < parsedActions.children.length; i++) {
  32734. var triggerParams;
  32735. var trigger = parsedActions.children[i];
  32736. if (trigger.properties.length > 0) {
  32737. var param = trigger.properties[0].value;
  32738. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  32739. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  32740. }
  32741. else
  32742. triggerParams = BABYLON.ActionManager[trigger.name];
  32743. for (var j = 0; j < trigger.children.length; j++) {
  32744. if (!trigger.detached)
  32745. traverse(trigger.children[j], triggerParams, null, null);
  32746. }
  32747. }
  32748. };
  32749. ActionManager.GetTriggerName = function (trigger) {
  32750. switch (trigger) {
  32751. case 0: return "NothingTrigger";
  32752. case 1: return "OnPickTrigger";
  32753. case 2: return "OnLeftPickTrigger";
  32754. case 3: return "OnRightPickTrigger";
  32755. case 4: return "OnCenterPickTrigger";
  32756. case 5: return "OnPickDownTrigger";
  32757. case 6: return "OnPickUpTrigger";
  32758. case 7: return "OnLongPressTrigger";
  32759. case 8: return "OnPointerOverTrigger";
  32760. case 9: return "OnPointerOutTrigger";
  32761. case 10: return "OnEveryFrameTrigger";
  32762. case 11: return "OnIntersectionEnterTrigger";
  32763. case 12: return "OnIntersectionExitTrigger";
  32764. case 13: return "OnKeyDownTrigger";
  32765. case 14: return "OnKeyUpTrigger";
  32766. case 15: return "OnPickOutTrigger";
  32767. default: return "";
  32768. }
  32769. };
  32770. // Statics
  32771. ActionManager._NothingTrigger = 0;
  32772. ActionManager._OnPickTrigger = 1;
  32773. ActionManager._OnLeftPickTrigger = 2;
  32774. ActionManager._OnRightPickTrigger = 3;
  32775. ActionManager._OnCenterPickTrigger = 4;
  32776. ActionManager._OnPickDownTrigger = 5;
  32777. ActionManager._OnPickUpTrigger = 6;
  32778. ActionManager._OnLongPressTrigger = 7;
  32779. ActionManager._OnPointerOverTrigger = 8;
  32780. ActionManager._OnPointerOutTrigger = 9;
  32781. ActionManager._OnEveryFrameTrigger = 10;
  32782. ActionManager._OnIntersectionEnterTrigger = 11;
  32783. ActionManager._OnIntersectionExitTrigger = 12;
  32784. ActionManager._OnKeyDownTrigger = 13;
  32785. ActionManager._OnKeyUpTrigger = 14;
  32786. ActionManager._OnPickOutTrigger = 15;
  32787. ActionManager.DragMovementThreshold = 10; // in pixels
  32788. ActionManager.LongPressDelay = 500; // in milliseconds
  32789. return ActionManager;
  32790. })();
  32791. BABYLON.ActionManager = ActionManager;
  32792. })(BABYLON || (BABYLON = {}));
  32793. var BABYLON;
  32794. (function (BABYLON) {
  32795. var InterpolateValueAction = (function (_super) {
  32796. __extends(InterpolateValueAction, _super);
  32797. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  32798. if (duration === void 0) { duration = 1000; }
  32799. _super.call(this, triggerOptions, condition);
  32800. this.propertyPath = propertyPath;
  32801. this.value = value;
  32802. this.duration = duration;
  32803. this.stopOtherAnimations = stopOtherAnimations;
  32804. this.onInterpolationDone = onInterpolationDone;
  32805. this._target = this._effectiveTarget = target;
  32806. }
  32807. InterpolateValueAction.prototype._prepare = function () {
  32808. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32809. this._property = this._getProperty(this.propertyPath);
  32810. };
  32811. InterpolateValueAction.prototype.execute = function () {
  32812. var scene = this._actionManager.getScene();
  32813. var keys = [
  32814. {
  32815. frame: 0,
  32816. value: this._effectiveTarget[this._property]
  32817. }, {
  32818. frame: 100,
  32819. value: this.value
  32820. }
  32821. ];
  32822. var dataType;
  32823. if (typeof this.value === "number") {
  32824. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  32825. }
  32826. else if (this.value instanceof BABYLON.Color3) {
  32827. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  32828. }
  32829. else if (this.value instanceof BABYLON.Vector3) {
  32830. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  32831. }
  32832. else if (this.value instanceof BABYLON.Matrix) {
  32833. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  32834. }
  32835. else if (this.value instanceof BABYLON.Quaternion) {
  32836. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  32837. }
  32838. else {
  32839. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  32840. return;
  32841. }
  32842. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  32843. animation.setKeys(keys);
  32844. if (this.stopOtherAnimations) {
  32845. scene.stopAnimation(this._effectiveTarget);
  32846. }
  32847. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  32848. };
  32849. InterpolateValueAction.prototype.serialize = function (parent) {
  32850. return _super.prototype._serialize.call(this, {
  32851. name: "InterpolateValueAction",
  32852. properties: [
  32853. BABYLON.Action._GetTargetProperty(this._target),
  32854. { name: "propertyPath", value: this.propertyPath },
  32855. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32856. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  32857. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  32858. ]
  32859. }, parent);
  32860. };
  32861. return InterpolateValueAction;
  32862. })(BABYLON.Action);
  32863. BABYLON.InterpolateValueAction = InterpolateValueAction;
  32864. })(BABYLON || (BABYLON = {}));
  32865. var BABYLON;
  32866. (function (BABYLON) {
  32867. var SwitchBooleanAction = (function (_super) {
  32868. __extends(SwitchBooleanAction, _super);
  32869. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  32870. _super.call(this, triggerOptions, condition);
  32871. this.propertyPath = propertyPath;
  32872. this._target = this._effectiveTarget = target;
  32873. }
  32874. SwitchBooleanAction.prototype._prepare = function () {
  32875. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32876. this._property = this._getProperty(this.propertyPath);
  32877. };
  32878. SwitchBooleanAction.prototype.execute = function () {
  32879. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  32880. };
  32881. SwitchBooleanAction.prototype.serialize = function (parent) {
  32882. return _super.prototype._serialize.call(this, {
  32883. name: "SwitchBooleanAction",
  32884. properties: [
  32885. BABYLON.Action._GetTargetProperty(this._target),
  32886. { name: "propertyPath", value: this.propertyPath }
  32887. ]
  32888. }, parent);
  32889. };
  32890. return SwitchBooleanAction;
  32891. })(BABYLON.Action);
  32892. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  32893. var SetStateAction = (function (_super) {
  32894. __extends(SetStateAction, _super);
  32895. function SetStateAction(triggerOptions, target, value, condition) {
  32896. _super.call(this, triggerOptions, condition);
  32897. this.value = value;
  32898. this._target = target;
  32899. }
  32900. SetStateAction.prototype.execute = function () {
  32901. this._target.state = this.value;
  32902. };
  32903. SetStateAction.prototype.serialize = function (parent) {
  32904. return _super.prototype._serialize.call(this, {
  32905. name: "SetStateAction",
  32906. properties: [
  32907. BABYLON.Action._GetTargetProperty(this._target),
  32908. { name: "value", value: this.value }
  32909. ]
  32910. }, parent);
  32911. };
  32912. return SetStateAction;
  32913. })(BABYLON.Action);
  32914. BABYLON.SetStateAction = SetStateAction;
  32915. var SetValueAction = (function (_super) {
  32916. __extends(SetValueAction, _super);
  32917. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  32918. _super.call(this, triggerOptions, condition);
  32919. this.propertyPath = propertyPath;
  32920. this.value = value;
  32921. this._target = this._effectiveTarget = target;
  32922. }
  32923. SetValueAction.prototype._prepare = function () {
  32924. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32925. this._property = this._getProperty(this.propertyPath);
  32926. };
  32927. SetValueAction.prototype.execute = function () {
  32928. this._effectiveTarget[this._property] = this.value;
  32929. if (this._target.markAsDirty) {
  32930. this._target.markAsDirty(this._property);
  32931. }
  32932. };
  32933. SetValueAction.prototype.serialize = function (parent) {
  32934. return _super.prototype._serialize.call(this, {
  32935. name: "SetValueAction",
  32936. properties: [
  32937. BABYLON.Action._GetTargetProperty(this._target),
  32938. { name: "propertyPath", value: this.propertyPath },
  32939. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32940. ]
  32941. }, parent);
  32942. };
  32943. return SetValueAction;
  32944. })(BABYLON.Action);
  32945. BABYLON.SetValueAction = SetValueAction;
  32946. var IncrementValueAction = (function (_super) {
  32947. __extends(IncrementValueAction, _super);
  32948. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  32949. _super.call(this, triggerOptions, condition);
  32950. this.propertyPath = propertyPath;
  32951. this.value = value;
  32952. this._target = this._effectiveTarget = target;
  32953. }
  32954. IncrementValueAction.prototype._prepare = function () {
  32955. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  32956. this._property = this._getProperty(this.propertyPath);
  32957. if (typeof this._effectiveTarget[this._property] !== "number") {
  32958. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  32959. }
  32960. };
  32961. IncrementValueAction.prototype.execute = function () {
  32962. this._effectiveTarget[this._property] += this.value;
  32963. if (this._target.markAsDirty) {
  32964. this._target.markAsDirty(this._property);
  32965. }
  32966. };
  32967. IncrementValueAction.prototype.serialize = function (parent) {
  32968. return _super.prototype._serialize.call(this, {
  32969. name: "IncrementValueAction",
  32970. properties: [
  32971. BABYLON.Action._GetTargetProperty(this._target),
  32972. { name: "propertyPath", value: this.propertyPath },
  32973. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  32974. ]
  32975. }, parent);
  32976. };
  32977. return IncrementValueAction;
  32978. })(BABYLON.Action);
  32979. BABYLON.IncrementValueAction = IncrementValueAction;
  32980. var PlayAnimationAction = (function (_super) {
  32981. __extends(PlayAnimationAction, _super);
  32982. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  32983. _super.call(this, triggerOptions, condition);
  32984. this.from = from;
  32985. this.to = to;
  32986. this.loop = loop;
  32987. this._target = target;
  32988. }
  32989. PlayAnimationAction.prototype._prepare = function () {
  32990. };
  32991. PlayAnimationAction.prototype.execute = function () {
  32992. var scene = this._actionManager.getScene();
  32993. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  32994. };
  32995. PlayAnimationAction.prototype.serialize = function (parent) {
  32996. return _super.prototype._serialize.call(this, {
  32997. name: "PlayAnimationAction",
  32998. properties: [
  32999. BABYLON.Action._GetTargetProperty(this._target),
  33000. { name: "from", value: String(this.from) },
  33001. { name: "to", value: String(this.to) },
  33002. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33003. ]
  33004. }, parent);
  33005. };
  33006. return PlayAnimationAction;
  33007. })(BABYLON.Action);
  33008. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33009. var StopAnimationAction = (function (_super) {
  33010. __extends(StopAnimationAction, _super);
  33011. function StopAnimationAction(triggerOptions, target, condition) {
  33012. _super.call(this, triggerOptions, condition);
  33013. this._target = target;
  33014. }
  33015. StopAnimationAction.prototype._prepare = function () {
  33016. };
  33017. StopAnimationAction.prototype.execute = function () {
  33018. var scene = this._actionManager.getScene();
  33019. scene.stopAnimation(this._target);
  33020. };
  33021. StopAnimationAction.prototype.serialize = function (parent) {
  33022. return _super.prototype._serialize.call(this, {
  33023. name: "StopAnimationAction",
  33024. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33025. }, parent);
  33026. };
  33027. return StopAnimationAction;
  33028. })(BABYLON.Action);
  33029. BABYLON.StopAnimationAction = StopAnimationAction;
  33030. var DoNothingAction = (function (_super) {
  33031. __extends(DoNothingAction, _super);
  33032. function DoNothingAction(triggerOptions, condition) {
  33033. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33034. _super.call(this, triggerOptions, condition);
  33035. }
  33036. DoNothingAction.prototype.execute = function () {
  33037. };
  33038. DoNothingAction.prototype.serialize = function (parent) {
  33039. return _super.prototype._serialize.call(this, {
  33040. name: "DoNothingAction",
  33041. properties: []
  33042. }, parent);
  33043. };
  33044. return DoNothingAction;
  33045. })(BABYLON.Action);
  33046. BABYLON.DoNothingAction = DoNothingAction;
  33047. var CombineAction = (function (_super) {
  33048. __extends(CombineAction, _super);
  33049. function CombineAction(triggerOptions, children, condition) {
  33050. _super.call(this, triggerOptions, condition);
  33051. this.children = children;
  33052. }
  33053. CombineAction.prototype._prepare = function () {
  33054. for (var index = 0; index < this.children.length; index++) {
  33055. this.children[index]._actionManager = this._actionManager;
  33056. this.children[index]._prepare();
  33057. }
  33058. };
  33059. CombineAction.prototype.execute = function (evt) {
  33060. for (var index = 0; index < this.children.length; index++) {
  33061. this.children[index].execute(evt);
  33062. }
  33063. };
  33064. CombineAction.prototype.serialize = function (parent) {
  33065. var serializationObject = _super.prototype._serialize.call(this, {
  33066. name: "CombineAction",
  33067. properties: [],
  33068. combine: []
  33069. }, parent);
  33070. for (var i = 0; i < this.children.length; i++) {
  33071. serializationObject.combine.push(this.children[i].serialize(null));
  33072. }
  33073. return serializationObject;
  33074. };
  33075. return CombineAction;
  33076. })(BABYLON.Action);
  33077. BABYLON.CombineAction = CombineAction;
  33078. var ExecuteCodeAction = (function (_super) {
  33079. __extends(ExecuteCodeAction, _super);
  33080. function ExecuteCodeAction(triggerOptions, func, condition) {
  33081. _super.call(this, triggerOptions, condition);
  33082. this.func = func;
  33083. }
  33084. ExecuteCodeAction.prototype.execute = function (evt) {
  33085. this.func(evt);
  33086. };
  33087. return ExecuteCodeAction;
  33088. })(BABYLON.Action);
  33089. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33090. var SetParentAction = (function (_super) {
  33091. __extends(SetParentAction, _super);
  33092. function SetParentAction(triggerOptions, target, parent, condition) {
  33093. _super.call(this, triggerOptions, condition);
  33094. this._target = target;
  33095. this._parent = parent;
  33096. }
  33097. SetParentAction.prototype._prepare = function () {
  33098. };
  33099. SetParentAction.prototype.execute = function () {
  33100. if (this._target.parent === this._parent) {
  33101. return;
  33102. }
  33103. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33104. invertParentWorldMatrix.invert();
  33105. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33106. this._target.parent = this._parent;
  33107. };
  33108. SetParentAction.prototype.serialize = function (parent) {
  33109. return _super.prototype._serialize.call(this, {
  33110. name: "SetParentAction",
  33111. properties: [
  33112. BABYLON.Action._GetTargetProperty(this._target),
  33113. BABYLON.Action._GetTargetProperty(this._parent),
  33114. ]
  33115. }, parent);
  33116. };
  33117. return SetParentAction;
  33118. })(BABYLON.Action);
  33119. BABYLON.SetParentAction = SetParentAction;
  33120. var PlaySoundAction = (function (_super) {
  33121. __extends(PlaySoundAction, _super);
  33122. function PlaySoundAction(triggerOptions, sound, condition) {
  33123. _super.call(this, triggerOptions, condition);
  33124. this._sound = sound;
  33125. }
  33126. PlaySoundAction.prototype._prepare = function () {
  33127. };
  33128. PlaySoundAction.prototype.execute = function () {
  33129. if (this._sound !== undefined)
  33130. this._sound.play();
  33131. };
  33132. PlaySoundAction.prototype.serialize = function (parent) {
  33133. return _super.prototype._serialize.call(this, {
  33134. name: "PlaySoundAction",
  33135. properties: [{ name: "sound", value: this._sound.name }]
  33136. }, parent);
  33137. };
  33138. return PlaySoundAction;
  33139. })(BABYLON.Action);
  33140. BABYLON.PlaySoundAction = PlaySoundAction;
  33141. var StopSoundAction = (function (_super) {
  33142. __extends(StopSoundAction, _super);
  33143. function StopSoundAction(triggerOptions, sound, condition) {
  33144. _super.call(this, triggerOptions, condition);
  33145. this._sound = sound;
  33146. }
  33147. StopSoundAction.prototype._prepare = function () {
  33148. };
  33149. StopSoundAction.prototype.execute = function () {
  33150. if (this._sound !== undefined)
  33151. this._sound.stop();
  33152. };
  33153. StopSoundAction.prototype.serialize = function (parent) {
  33154. return _super.prototype._serialize.call(this, {
  33155. name: "StopSoundAction",
  33156. properties: [{ name: "sound", value: this._sound.name }]
  33157. }, parent);
  33158. };
  33159. return StopSoundAction;
  33160. })(BABYLON.Action);
  33161. BABYLON.StopSoundAction = StopSoundAction;
  33162. })(BABYLON || (BABYLON = {}));
  33163. var BABYLON;
  33164. (function (BABYLON) {
  33165. var Geometry = (function () {
  33166. function Geometry(id, scene, vertexData, updatable, mesh) {
  33167. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33168. this._totalVertices = 0;
  33169. this._isDisposed = false;
  33170. this.id = id;
  33171. this._engine = scene.getEngine();
  33172. this._meshes = [];
  33173. this._scene = scene;
  33174. //Init vertex buffer cache
  33175. this._vertexBuffers = {};
  33176. this._indices = [];
  33177. // vertexData
  33178. if (vertexData) {
  33179. this.setAllVerticesData(vertexData, updatable);
  33180. }
  33181. else {
  33182. this._totalVertices = 0;
  33183. this._indices = [];
  33184. }
  33185. // applyToMesh
  33186. if (mesh) {
  33187. if (mesh instanceof BABYLON.LinesMesh) {
  33188. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33189. this.updateExtend();
  33190. }
  33191. this.applyToMesh(mesh);
  33192. mesh.computeWorldMatrix(true);
  33193. }
  33194. }
  33195. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33196. /**
  33197. * 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
  33198. * @returns The Bias Vector
  33199. */
  33200. get: function () {
  33201. return this._boundingBias;
  33202. },
  33203. set: function (value) {
  33204. if (this._boundingBias && this._boundingBias.equals(value)) {
  33205. return;
  33206. }
  33207. this._boundingBias = value.clone();
  33208. this.updateBoundingInfo(true, null);
  33209. },
  33210. enumerable: true,
  33211. configurable: true
  33212. });
  33213. Object.defineProperty(Geometry.prototype, "extend", {
  33214. get: function () {
  33215. return this._extend;
  33216. },
  33217. enumerable: true,
  33218. configurable: true
  33219. });
  33220. Geometry.prototype.getScene = function () {
  33221. return this._scene;
  33222. };
  33223. Geometry.prototype.getEngine = function () {
  33224. return this._engine;
  33225. };
  33226. Geometry.prototype.isReady = function () {
  33227. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33228. };
  33229. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33230. vertexData.applyToGeometry(this, updatable);
  33231. this.notifyUpdate();
  33232. };
  33233. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33234. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33235. this.setVerticesBuffer(buffer);
  33236. };
  33237. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33238. var kind = buffer.getKind();
  33239. if (this._vertexBuffers[kind]) {
  33240. this._vertexBuffers[kind].dispose();
  33241. }
  33242. this._vertexBuffers[kind] = buffer;
  33243. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33244. var data = buffer.getData();
  33245. var stride = buffer.getStrideSize();
  33246. this._totalVertices = data.length / stride;
  33247. this.updateExtend(data, stride);
  33248. var meshes = this._meshes;
  33249. var numOfMeshes = meshes.length;
  33250. for (var index = 0; index < numOfMeshes; index++) {
  33251. var mesh = meshes[index];
  33252. mesh._resetPointsArrayCache();
  33253. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33254. mesh._createGlobalSubMesh();
  33255. mesh.computeWorldMatrix(true);
  33256. }
  33257. }
  33258. this.notifyUpdate(kind);
  33259. };
  33260. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33261. var vertexBuffer = this.getVertexBuffer(kind);
  33262. if (!vertexBuffer) {
  33263. return;
  33264. }
  33265. vertexBuffer.updateDirectly(data, offset);
  33266. this.notifyUpdate(kind);
  33267. };
  33268. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33269. var vertexBuffer = this.getVertexBuffer(kind);
  33270. if (!vertexBuffer) {
  33271. return;
  33272. }
  33273. vertexBuffer.update(data);
  33274. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33275. var stride = vertexBuffer.getStrideSize();
  33276. this._totalVertices = data.length / stride;
  33277. this.updateBoundingInfo(updateExtends, data);
  33278. }
  33279. this.notifyUpdate(kind);
  33280. };
  33281. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33282. if (updateExtends) {
  33283. this.updateExtend(data);
  33284. }
  33285. var meshes = this._meshes;
  33286. var numOfMeshes = meshes.length;
  33287. for (var index = 0; index < numOfMeshes; index++) {
  33288. var mesh = meshes[index];
  33289. mesh._resetPointsArrayCache();
  33290. if (updateExtends) {
  33291. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33292. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33293. var subMesh = mesh.subMeshes[subIndex];
  33294. subMesh.refreshBoundingInfo();
  33295. }
  33296. }
  33297. }
  33298. };
  33299. Geometry.prototype.getTotalVertices = function () {
  33300. if (!this.isReady()) {
  33301. return 0;
  33302. }
  33303. return this._totalVertices;
  33304. };
  33305. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33306. var vertexBuffer = this.getVertexBuffer(kind);
  33307. if (!vertexBuffer) {
  33308. return null;
  33309. }
  33310. var orig = vertexBuffer.getData();
  33311. if (!copyWhenShared || this._meshes.length === 1) {
  33312. return orig;
  33313. }
  33314. else {
  33315. var len = orig.length;
  33316. var copy = [];
  33317. for (var i = 0; i < len; i++) {
  33318. copy.push(orig[i]);
  33319. }
  33320. return copy;
  33321. }
  33322. };
  33323. Geometry.prototype.getVertexBuffer = function (kind) {
  33324. if (!this.isReady()) {
  33325. return null;
  33326. }
  33327. return this._vertexBuffers[kind];
  33328. };
  33329. Geometry.prototype.getVertexBuffers = function () {
  33330. if (!this.isReady()) {
  33331. return null;
  33332. }
  33333. return this._vertexBuffers;
  33334. };
  33335. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33336. if (!this._vertexBuffers) {
  33337. if (this._delayInfo) {
  33338. return this._delayInfo.indexOf(kind) !== -1;
  33339. }
  33340. return false;
  33341. }
  33342. return this._vertexBuffers[kind] !== undefined;
  33343. };
  33344. Geometry.prototype.getVerticesDataKinds = function () {
  33345. var result = [];
  33346. var kind;
  33347. if (!this._vertexBuffers && this._delayInfo) {
  33348. for (kind in this._delayInfo) {
  33349. result.push(kind);
  33350. }
  33351. }
  33352. else {
  33353. for (kind in this._vertexBuffers) {
  33354. result.push(kind);
  33355. }
  33356. }
  33357. return result;
  33358. };
  33359. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33360. if (this._indexBuffer) {
  33361. this._engine._releaseBuffer(this._indexBuffer);
  33362. }
  33363. this._indices = indices;
  33364. if (this._meshes.length !== 0 && this._indices) {
  33365. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33366. }
  33367. if (totalVertices !== undefined) {
  33368. this._totalVertices = totalVertices;
  33369. }
  33370. var meshes = this._meshes;
  33371. var numOfMeshes = meshes.length;
  33372. for (var index = 0; index < numOfMeshes; index++) {
  33373. meshes[index]._createGlobalSubMesh();
  33374. }
  33375. this.notifyUpdate();
  33376. };
  33377. Geometry.prototype.getTotalIndices = function () {
  33378. if (!this.isReady()) {
  33379. return 0;
  33380. }
  33381. return this._indices.length;
  33382. };
  33383. Geometry.prototype.getIndices = function (copyWhenShared) {
  33384. if (!this.isReady()) {
  33385. return null;
  33386. }
  33387. var orig = this._indices;
  33388. if (!copyWhenShared || this._meshes.length === 1) {
  33389. return orig;
  33390. }
  33391. else {
  33392. var len = orig.length;
  33393. var copy = [];
  33394. for (var i = 0; i < len; i++) {
  33395. copy.push(orig[i]);
  33396. }
  33397. return copy;
  33398. }
  33399. };
  33400. Geometry.prototype.getIndexBuffer = function () {
  33401. if (!this.isReady()) {
  33402. return null;
  33403. }
  33404. return this._indexBuffer;
  33405. };
  33406. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  33407. var meshes = this._meshes;
  33408. var index = meshes.indexOf(mesh);
  33409. if (index === -1) {
  33410. return;
  33411. }
  33412. for (var kind in this._vertexBuffers) {
  33413. this._vertexBuffers[kind].dispose();
  33414. }
  33415. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  33416. this._indexBuffer = null;
  33417. }
  33418. meshes.splice(index, 1);
  33419. mesh._geometry = null;
  33420. if (meshes.length === 0 && shouldDispose) {
  33421. this.dispose();
  33422. }
  33423. };
  33424. Geometry.prototype.applyToMesh = function (mesh) {
  33425. if (mesh._geometry === this) {
  33426. return;
  33427. }
  33428. var previousGeometry = mesh._geometry;
  33429. if (previousGeometry) {
  33430. previousGeometry.releaseForMesh(mesh);
  33431. }
  33432. var meshes = this._meshes;
  33433. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  33434. mesh._geometry = this;
  33435. this._scene.pushGeometry(this);
  33436. meshes.push(mesh);
  33437. if (this.isReady()) {
  33438. this._applyToMesh(mesh);
  33439. }
  33440. else {
  33441. mesh._boundingInfo = this._boundingInfo;
  33442. }
  33443. };
  33444. Geometry.prototype.updateExtend = function (data, stride) {
  33445. if (data === void 0) { data = null; }
  33446. if (!data) {
  33447. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  33448. }
  33449. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  33450. };
  33451. Geometry.prototype._applyToMesh = function (mesh) {
  33452. var numOfMeshes = this._meshes.length;
  33453. // vertexBuffers
  33454. for (var kind in this._vertexBuffers) {
  33455. if (numOfMeshes === 1) {
  33456. this._vertexBuffers[kind].create();
  33457. }
  33458. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  33459. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33460. mesh._resetPointsArrayCache();
  33461. if (!this._extend) {
  33462. this.updateExtend(this._vertexBuffers[kind].getData());
  33463. }
  33464. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33465. mesh._createGlobalSubMesh();
  33466. //bounding info was just created again, world matrix should be applied again.
  33467. mesh._updateBoundingInfo();
  33468. }
  33469. }
  33470. // indexBuffer
  33471. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  33472. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33473. }
  33474. if (this._indexBuffer) {
  33475. this._indexBuffer.references = numOfMeshes;
  33476. }
  33477. };
  33478. Geometry.prototype.notifyUpdate = function (kind) {
  33479. if (this.onGeometryUpdated) {
  33480. this.onGeometryUpdated(this, kind);
  33481. }
  33482. };
  33483. Geometry.prototype.load = function (scene, onLoaded) {
  33484. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33485. return;
  33486. }
  33487. if (this.isReady()) {
  33488. if (onLoaded) {
  33489. onLoaded();
  33490. }
  33491. return;
  33492. }
  33493. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33494. this._queueLoad(scene, onLoaded);
  33495. };
  33496. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  33497. var _this = this;
  33498. scene._addPendingData(this);
  33499. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33500. _this._delayLoadingFunction(JSON.parse(data), _this);
  33501. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33502. _this._delayInfo = [];
  33503. scene._removePendingData(_this);
  33504. var meshes = _this._meshes;
  33505. var numOfMeshes = meshes.length;
  33506. for (var index = 0; index < numOfMeshes; index++) {
  33507. _this._applyToMesh(meshes[index]);
  33508. }
  33509. if (onLoaded) {
  33510. onLoaded();
  33511. }
  33512. }, function () { }, scene.database);
  33513. };
  33514. /**
  33515. * Invert the geometry to move from a right handed system to a left handed one.
  33516. */
  33517. Geometry.prototype.toLeftHanded = function () {
  33518. // Flip faces
  33519. var tIndices = this.getIndices(false);
  33520. if (tIndices != null && tIndices.length > 0) {
  33521. for (var i = 0; i < tIndices.length; i += 3) {
  33522. var tTemp = tIndices[i + 0];
  33523. tIndices[i + 0] = tIndices[i + 2];
  33524. tIndices[i + 2] = tTemp;
  33525. }
  33526. this.setIndices(tIndices);
  33527. }
  33528. // Negate position.z
  33529. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  33530. if (tPositions != null && tPositions.length > 0) {
  33531. for (var i = 0; i < tPositions.length; i += 3) {
  33532. tPositions[i + 2] = -tPositions[i + 2];
  33533. }
  33534. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  33535. }
  33536. // Negate normal.z
  33537. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  33538. if (tNormals != null && tNormals.length > 0) {
  33539. for (var i = 0; i < tNormals.length; i += 3) {
  33540. tNormals[i + 2] = -tNormals[i + 2];
  33541. }
  33542. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  33543. }
  33544. };
  33545. Geometry.prototype.isDisposed = function () {
  33546. return this._isDisposed;
  33547. };
  33548. Geometry.prototype.dispose = function () {
  33549. var meshes = this._meshes;
  33550. var numOfMeshes = meshes.length;
  33551. var index;
  33552. for (index = 0; index < numOfMeshes; index++) {
  33553. this.releaseForMesh(meshes[index]);
  33554. }
  33555. this._meshes = [];
  33556. for (var kind in this._vertexBuffers) {
  33557. this._vertexBuffers[kind].dispose();
  33558. }
  33559. this._vertexBuffers = {};
  33560. this._totalVertices = 0;
  33561. if (this._indexBuffer) {
  33562. this._engine._releaseBuffer(this._indexBuffer);
  33563. }
  33564. this._indexBuffer = null;
  33565. this._indices = [];
  33566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33567. this.delayLoadingFile = null;
  33568. this._delayLoadingFunction = null;
  33569. this._delayInfo = [];
  33570. this._boundingInfo = null;
  33571. this._scene.removeGeometry(this);
  33572. this._isDisposed = true;
  33573. };
  33574. Geometry.prototype.copy = function (id) {
  33575. var vertexData = new BABYLON.VertexData();
  33576. vertexData.indices = [];
  33577. var indices = this.getIndices();
  33578. for (var index = 0; index < indices.length; index++) {
  33579. vertexData.indices.push(indices[index]);
  33580. }
  33581. var updatable = false;
  33582. var stopChecking = false;
  33583. var kind;
  33584. for (kind in this._vertexBuffers) {
  33585. // using slice() to make a copy of the array and not just reference it
  33586. var data = this.getVerticesData(kind);
  33587. if (data instanceof Float32Array) {
  33588. vertexData.set(new Float32Array(data), kind);
  33589. }
  33590. else {
  33591. vertexData.set(data.slice(0), kind);
  33592. }
  33593. if (!stopChecking) {
  33594. updatable = this.getVertexBuffer(kind).isUpdatable();
  33595. stopChecking = !updatable;
  33596. }
  33597. }
  33598. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  33599. geometry.delayLoadState = this.delayLoadState;
  33600. geometry.delayLoadingFile = this.delayLoadingFile;
  33601. geometry._delayLoadingFunction = this._delayLoadingFunction;
  33602. for (kind in this._delayInfo) {
  33603. geometry._delayInfo = geometry._delayInfo || [];
  33604. geometry._delayInfo.push(kind);
  33605. }
  33606. // Bounding info
  33607. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33608. return geometry;
  33609. };
  33610. Geometry.prototype.serialize = function () {
  33611. var serializationObject = {};
  33612. serializationObject.id = this.id;
  33613. if (BABYLON.Tags.HasTags(this)) {
  33614. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33615. }
  33616. return serializationObject;
  33617. };
  33618. Geometry.prototype.serializeVerticeData = function () {
  33619. var serializationObject = this.serialize();
  33620. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33621. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33622. }
  33623. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33624. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33625. }
  33626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33627. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33628. }
  33629. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33630. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  33631. }
  33632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33633. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  33634. }
  33635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33636. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  33637. }
  33638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33639. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  33640. }
  33641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33642. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  33643. }
  33644. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33645. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  33646. }
  33647. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33648. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33649. serializationObject.matricesIndices._isExpanded = true;
  33650. }
  33651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33652. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33653. }
  33654. serializationObject.indices = this.getIndices();
  33655. return serializationObject;
  33656. };
  33657. // Statics
  33658. Geometry.ExtractFromMesh = function (mesh, id) {
  33659. var geometry = mesh._geometry;
  33660. if (!geometry) {
  33661. return null;
  33662. }
  33663. return geometry.copy(id);
  33664. };
  33665. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33666. // be aware Math.random() could cause collisions
  33667. Geometry.RandomId = function () {
  33668. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  33669. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  33670. return v.toString(16);
  33671. });
  33672. };
  33673. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  33674. var scene = mesh.getScene();
  33675. // Geometry
  33676. var geometryId = parsedGeometry.geometryId;
  33677. if (geometryId) {
  33678. var geometry = scene.getGeometryByID(geometryId);
  33679. if (geometry) {
  33680. geometry.applyToMesh(mesh);
  33681. }
  33682. }
  33683. else if (parsedGeometry instanceof ArrayBuffer) {
  33684. var binaryInfo = mesh._binaryInfo;
  33685. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33686. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33687. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33688. }
  33689. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33690. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33691. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33692. }
  33693. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33694. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33695. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33696. }
  33697. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33698. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33699. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33700. }
  33701. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33702. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33703. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33704. }
  33705. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33706. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33707. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33708. }
  33709. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33710. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33711. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33712. }
  33713. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33714. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33715. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33716. }
  33717. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33718. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33719. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33720. }
  33721. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33722. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33723. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33724. }
  33725. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33726. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33727. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33728. }
  33729. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33730. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33731. mesh.setIndices(indicesData);
  33732. }
  33733. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33734. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33735. mesh.subMeshes = [];
  33736. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33737. var materialIndex = subMeshesData[(i * 5) + 0];
  33738. var verticesStart = subMeshesData[(i * 5) + 1];
  33739. var verticesCount = subMeshesData[(i * 5) + 2];
  33740. var indexStart = subMeshesData[(i * 5) + 3];
  33741. var indexCount = subMeshesData[(i * 5) + 4];
  33742. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33743. }
  33744. }
  33745. }
  33746. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33747. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  33748. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  33749. if (parsedGeometry.uvs) {
  33750. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  33751. }
  33752. if (parsedGeometry.uvs2) {
  33753. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  33754. }
  33755. if (parsedGeometry.uvs3) {
  33756. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  33757. }
  33758. if (parsedGeometry.uvs4) {
  33759. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  33760. }
  33761. if (parsedGeometry.uvs5) {
  33762. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  33763. }
  33764. if (parsedGeometry.uvs6) {
  33765. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  33766. }
  33767. if (parsedGeometry.colors) {
  33768. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  33769. }
  33770. if (parsedGeometry.matricesIndices) {
  33771. if (!parsedGeometry.matricesIndices._isExpanded) {
  33772. var floatIndices = [];
  33773. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33774. var matricesIndex = parsedGeometry.matricesIndices[i];
  33775. floatIndices.push(matricesIndex & 0x000000FF);
  33776. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33777. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33778. floatIndices.push(matricesIndex >> 24);
  33779. }
  33780. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  33781. }
  33782. else {
  33783. delete parsedGeometry.matricesIndices._isExpanded;
  33784. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  33785. }
  33786. }
  33787. if (parsedGeometry.matricesIndicesExtra) {
  33788. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33789. var floatIndices = [];
  33790. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33791. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33792. floatIndices.push(matricesIndex & 0x000000FF);
  33793. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33794. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33795. floatIndices.push(matricesIndex >> 24);
  33796. }
  33797. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  33798. }
  33799. else {
  33800. delete parsedGeometry.matricesIndices._isExpanded;
  33801. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  33802. }
  33803. }
  33804. if (parsedGeometry.matricesWeights) {
  33805. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  33806. }
  33807. if (parsedGeometry.matricesWeightsExtra) {
  33808. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  33809. }
  33810. mesh.setIndices(parsedGeometry.indices);
  33811. }
  33812. // SubMeshes
  33813. if (parsedGeometry.subMeshes) {
  33814. mesh.subMeshes = [];
  33815. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33816. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33817. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33818. }
  33819. }
  33820. // Flat shading
  33821. if (mesh._shouldGenerateFlatShading) {
  33822. mesh.convertToFlatShadedMesh();
  33823. delete mesh._shouldGenerateFlatShading;
  33824. }
  33825. // Update
  33826. mesh.computeWorldMatrix(true);
  33827. // Octree
  33828. if (scene['_selectionOctree']) {
  33829. scene['_selectionOctree'].addMesh(mesh);
  33830. }
  33831. };
  33832. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33833. if (scene.getGeometryByID(parsedVertexData.id)) {
  33834. return null; // null since geometry could be something else than a box...
  33835. }
  33836. var geometry = new Geometry(parsedVertexData.id, scene);
  33837. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33838. if (parsedVertexData.delayLoadingFile) {
  33839. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33840. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33841. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33842. geometry._delayInfo = [];
  33843. if (parsedVertexData.hasUVs) {
  33844. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33845. }
  33846. if (parsedVertexData.hasUVs2) {
  33847. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33848. }
  33849. if (parsedVertexData.hasUVs3) {
  33850. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33851. }
  33852. if (parsedVertexData.hasUVs4) {
  33853. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33854. }
  33855. if (parsedVertexData.hasUVs5) {
  33856. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33857. }
  33858. if (parsedVertexData.hasUVs6) {
  33859. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33860. }
  33861. if (parsedVertexData.hasColors) {
  33862. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33863. }
  33864. if (parsedVertexData.hasMatricesIndices) {
  33865. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33866. }
  33867. if (parsedVertexData.hasMatricesWeights) {
  33868. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33869. }
  33870. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33871. }
  33872. else {
  33873. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33874. }
  33875. scene.pushGeometry(geometry, true);
  33876. return geometry;
  33877. };
  33878. return Geometry;
  33879. })();
  33880. BABYLON.Geometry = Geometry;
  33881. /////// Primitives //////////////////////////////////////////////
  33882. var Geometry;
  33883. (function (Geometry) {
  33884. var Primitives;
  33885. (function (Primitives) {
  33886. /// Abstract class
  33887. var _Primitive = (function (_super) {
  33888. __extends(_Primitive, _super);
  33889. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  33890. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  33891. this._canBeRegenerated = _canBeRegenerated;
  33892. this._beingRegenerated = true;
  33893. this.regenerate();
  33894. this._beingRegenerated = false;
  33895. }
  33896. _Primitive.prototype.canBeRegenerated = function () {
  33897. return this._canBeRegenerated;
  33898. };
  33899. _Primitive.prototype.regenerate = function () {
  33900. if (!this._canBeRegenerated) {
  33901. return;
  33902. }
  33903. this._beingRegenerated = true;
  33904. this.setAllVerticesData(this._regenerateVertexData(), false);
  33905. this._beingRegenerated = false;
  33906. };
  33907. _Primitive.prototype.asNewGeometry = function (id) {
  33908. return _super.prototype.copy.call(this, id);
  33909. };
  33910. // overrides
  33911. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  33912. if (!this._beingRegenerated) {
  33913. return;
  33914. }
  33915. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33916. };
  33917. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  33918. if (!this._beingRegenerated) {
  33919. return;
  33920. }
  33921. _super.prototype.setVerticesData.call(this, kind, data, false);
  33922. };
  33923. // to override
  33924. // protected
  33925. _Primitive.prototype._regenerateVertexData = function () {
  33926. throw new Error("Abstract method");
  33927. };
  33928. _Primitive.prototype.copy = function (id) {
  33929. throw new Error("Must be overriden in sub-classes.");
  33930. };
  33931. _Primitive.prototype.serialize = function () {
  33932. var serializationObject = _super.prototype.serialize.call(this);
  33933. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33934. return serializationObject;
  33935. };
  33936. return _Primitive;
  33937. })(Geometry);
  33938. Primitives._Primitive = _Primitive;
  33939. var Ribbon = (function (_super) {
  33940. __extends(Ribbon, _super);
  33941. // Members
  33942. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  33943. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33944. _super.call(this, id, scene, canBeRegenerated, mesh);
  33945. this.pathArray = pathArray;
  33946. this.closeArray = closeArray;
  33947. this.closePath = closePath;
  33948. this.offset = offset;
  33949. this.side = side;
  33950. }
  33951. Ribbon.prototype._regenerateVertexData = function () {
  33952. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33953. };
  33954. Ribbon.prototype.copy = function (id) {
  33955. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  33956. };
  33957. return Ribbon;
  33958. })(_Primitive);
  33959. Primitives.Ribbon = Ribbon;
  33960. var Box = (function (_super) {
  33961. __extends(Box, _super);
  33962. // Members
  33963. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  33964. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33965. _super.call(this, id, scene, canBeRegenerated, mesh);
  33966. this.size = size;
  33967. this.side = side;
  33968. }
  33969. Box.prototype._regenerateVertexData = function () {
  33970. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33971. };
  33972. Box.prototype.copy = function (id) {
  33973. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33974. };
  33975. Box.prototype.serialize = function () {
  33976. var serializationObject = _super.prototype.serialize.call(this);
  33977. serializationObject.size = this.size;
  33978. return serializationObject;
  33979. };
  33980. Box.Parse = function (parsedBox, scene) {
  33981. if (scene.getGeometryByID(parsedBox.id)) {
  33982. return null; // null since geometry could be something else than a box...
  33983. }
  33984. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33985. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33986. scene.pushGeometry(box, true);
  33987. return box;
  33988. };
  33989. return Box;
  33990. })(_Primitive);
  33991. Primitives.Box = Box;
  33992. var Sphere = (function (_super) {
  33993. __extends(Sphere, _super);
  33994. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  33995. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33996. _super.call(this, id, scene, canBeRegenerated, mesh);
  33997. this.segments = segments;
  33998. this.diameter = diameter;
  33999. this.side = side;
  34000. }
  34001. Sphere.prototype._regenerateVertexData = function () {
  34002. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34003. };
  34004. Sphere.prototype.copy = function (id) {
  34005. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34006. };
  34007. Sphere.prototype.serialize = function () {
  34008. var serializationObject = _super.prototype.serialize.call(this);
  34009. serializationObject.segments = this.segments;
  34010. serializationObject.diameter = this.diameter;
  34011. return serializationObject;
  34012. };
  34013. Sphere.Parse = function (parsedSphere, scene) {
  34014. if (scene.getGeometryByID(parsedSphere.id)) {
  34015. return null; // null since geometry could be something else than a sphere...
  34016. }
  34017. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34018. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34019. scene.pushGeometry(sphere, true);
  34020. return sphere;
  34021. };
  34022. return Sphere;
  34023. })(_Primitive);
  34024. Primitives.Sphere = Sphere;
  34025. var Disc = (function (_super) {
  34026. __extends(Disc, _super);
  34027. // Members
  34028. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34029. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34030. _super.call(this, id, scene, canBeRegenerated, mesh);
  34031. this.radius = radius;
  34032. this.tessellation = tessellation;
  34033. this.side = side;
  34034. }
  34035. Disc.prototype._regenerateVertexData = function () {
  34036. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34037. };
  34038. Disc.prototype.copy = function (id) {
  34039. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34040. };
  34041. return Disc;
  34042. })(_Primitive);
  34043. Primitives.Disc = Disc;
  34044. var Cylinder = (function (_super) {
  34045. __extends(Cylinder, _super);
  34046. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34047. if (subdivisions === void 0) { subdivisions = 1; }
  34048. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34049. _super.call(this, id, scene, canBeRegenerated, mesh);
  34050. this.height = height;
  34051. this.diameterTop = diameterTop;
  34052. this.diameterBottom = diameterBottom;
  34053. this.tessellation = tessellation;
  34054. this.subdivisions = subdivisions;
  34055. this.side = side;
  34056. }
  34057. Cylinder.prototype._regenerateVertexData = function () {
  34058. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34059. };
  34060. Cylinder.prototype.copy = function (id) {
  34061. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34062. };
  34063. Cylinder.prototype.serialize = function () {
  34064. var serializationObject = _super.prototype.serialize.call(this);
  34065. serializationObject.height = this.height;
  34066. serializationObject.diameterTop = this.diameterTop;
  34067. serializationObject.diameterBottom = this.diameterBottom;
  34068. serializationObject.tessellation = this.tessellation;
  34069. return serializationObject;
  34070. };
  34071. Cylinder.Parse = function (parsedCylinder, scene) {
  34072. if (scene.getGeometryByID(parsedCylinder.id)) {
  34073. return null; // null since geometry could be something else than a cylinder...
  34074. }
  34075. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34076. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34077. scene.pushGeometry(cylinder, true);
  34078. return cylinder;
  34079. };
  34080. return Cylinder;
  34081. })(_Primitive);
  34082. Primitives.Cylinder = Cylinder;
  34083. var Torus = (function (_super) {
  34084. __extends(Torus, _super);
  34085. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34086. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34087. _super.call(this, id, scene, canBeRegenerated, mesh);
  34088. this.diameter = diameter;
  34089. this.thickness = thickness;
  34090. this.tessellation = tessellation;
  34091. this.side = side;
  34092. }
  34093. Torus.prototype._regenerateVertexData = function () {
  34094. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34095. };
  34096. Torus.prototype.copy = function (id) {
  34097. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34098. };
  34099. Torus.prototype.serialize = function () {
  34100. var serializationObject = _super.prototype.serialize.call(this);
  34101. serializationObject.diameter = this.diameter;
  34102. serializationObject.thickness = this.thickness;
  34103. serializationObject.tessellation = this.tessellation;
  34104. return serializationObject;
  34105. };
  34106. Torus.Parse = function (parsedTorus, scene) {
  34107. if (scene.getGeometryByID(parsedTorus.id)) {
  34108. return null; // null since geometry could be something else than a torus...
  34109. }
  34110. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34111. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34112. scene.pushGeometry(torus, true);
  34113. return torus;
  34114. };
  34115. return Torus;
  34116. })(_Primitive);
  34117. Primitives.Torus = Torus;
  34118. var Ground = (function (_super) {
  34119. __extends(Ground, _super);
  34120. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34121. _super.call(this, id, scene, canBeRegenerated, mesh);
  34122. this.width = width;
  34123. this.height = height;
  34124. this.subdivisions = subdivisions;
  34125. }
  34126. Ground.prototype._regenerateVertexData = function () {
  34127. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34128. };
  34129. Ground.prototype.copy = function (id) {
  34130. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34131. };
  34132. Ground.prototype.serialize = function () {
  34133. var serializationObject = _super.prototype.serialize.call(this);
  34134. serializationObject.width = this.width;
  34135. serializationObject.height = this.height;
  34136. serializationObject.subdivisions = this.subdivisions;
  34137. return serializationObject;
  34138. };
  34139. Ground.Parse = function (parsedGround, scene) {
  34140. if (scene.getGeometryByID(parsedGround.id)) {
  34141. return null; // null since geometry could be something else than a ground...
  34142. }
  34143. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34144. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34145. scene.pushGeometry(ground, true);
  34146. return ground;
  34147. };
  34148. return Ground;
  34149. })(_Primitive);
  34150. Primitives.Ground = Ground;
  34151. var TiledGround = (function (_super) {
  34152. __extends(TiledGround, _super);
  34153. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34154. _super.call(this, id, scene, canBeRegenerated, mesh);
  34155. this.xmin = xmin;
  34156. this.zmin = zmin;
  34157. this.xmax = xmax;
  34158. this.zmax = zmax;
  34159. this.subdivisions = subdivisions;
  34160. this.precision = precision;
  34161. }
  34162. TiledGround.prototype._regenerateVertexData = function () {
  34163. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34164. };
  34165. TiledGround.prototype.copy = function (id) {
  34166. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34167. };
  34168. return TiledGround;
  34169. })(_Primitive);
  34170. Primitives.TiledGround = TiledGround;
  34171. var Plane = (function (_super) {
  34172. __extends(Plane, _super);
  34173. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34174. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34175. _super.call(this, id, scene, canBeRegenerated, mesh);
  34176. this.size = size;
  34177. this.side = side;
  34178. }
  34179. Plane.prototype._regenerateVertexData = function () {
  34180. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34181. };
  34182. Plane.prototype.copy = function (id) {
  34183. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34184. };
  34185. Plane.prototype.serialize = function () {
  34186. var serializationObject = _super.prototype.serialize.call(this);
  34187. serializationObject.size = this.size;
  34188. return serializationObject;
  34189. };
  34190. Plane.Parse = function (parsedPlane, scene) {
  34191. if (scene.getGeometryByID(parsedPlane.id)) {
  34192. return null; // null since geometry could be something else than a ground...
  34193. }
  34194. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34195. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34196. scene.pushGeometry(plane, true);
  34197. return plane;
  34198. };
  34199. return Plane;
  34200. })(_Primitive);
  34201. Primitives.Plane = Plane;
  34202. var TorusKnot = (function (_super) {
  34203. __extends(TorusKnot, _super);
  34204. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34205. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34206. _super.call(this, id, scene, canBeRegenerated, mesh);
  34207. this.radius = radius;
  34208. this.tube = tube;
  34209. this.radialSegments = radialSegments;
  34210. this.tubularSegments = tubularSegments;
  34211. this.p = p;
  34212. this.q = q;
  34213. this.side = side;
  34214. }
  34215. TorusKnot.prototype._regenerateVertexData = function () {
  34216. 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 });
  34217. };
  34218. TorusKnot.prototype.copy = function (id) {
  34219. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34220. };
  34221. TorusKnot.prototype.serialize = function () {
  34222. var serializationObject = _super.prototype.serialize.call(this);
  34223. serializationObject.radius = this.radius;
  34224. serializationObject.tube = this.tube;
  34225. serializationObject.radialSegments = this.radialSegments;
  34226. serializationObject.tubularSegments = this.tubularSegments;
  34227. serializationObject.p = this.p;
  34228. serializationObject.q = this.q;
  34229. return serializationObject;
  34230. };
  34231. ;
  34232. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34233. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34234. return null; // null since geometry could be something else than a ground...
  34235. }
  34236. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34237. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34238. scene.pushGeometry(torusKnot, true);
  34239. return torusKnot;
  34240. };
  34241. return TorusKnot;
  34242. })(_Primitive);
  34243. Primitives.TorusKnot = TorusKnot;
  34244. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34245. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34246. })(BABYLON || (BABYLON = {}));
  34247. var BABYLON;
  34248. (function (BABYLON) {
  34249. var GroundMesh = (function (_super) {
  34250. __extends(GroundMesh, _super);
  34251. function GroundMesh(name, scene) {
  34252. _super.call(this, name, scene);
  34253. this.generateOctree = false;
  34254. this._worldInverse = new BABYLON.Matrix();
  34255. }
  34256. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34257. get: function () {
  34258. return this._subdivisions;
  34259. },
  34260. enumerable: true,
  34261. configurable: true
  34262. });
  34263. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34264. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34265. this._subdivisions = chunksCount;
  34266. this.subdivide(this._subdivisions);
  34267. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34268. };
  34269. /**
  34270. * Returns a height (y) value in the Worl system :
  34271. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34272. * Returns the ground y position if (x, z) are outside the ground surface.
  34273. * Not pertinent if the ground is rotated.
  34274. */
  34275. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34276. // express x and y in the ground local system
  34277. x -= this.position.x;
  34278. z -= this.position.z;
  34279. x /= this.scaling.x;
  34280. z /= this.scaling.z;
  34281. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34282. return this.position.y;
  34283. }
  34284. if (!this._heightQuads || this._heightQuads.length == 0) {
  34285. this._initHeightQuads();
  34286. this._computeHeightQuads();
  34287. }
  34288. var facet = this._getFacetAt(x, z);
  34289. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34290. // return y in the World system
  34291. return y * this.scaling.y + this.position.y;
  34292. };
  34293. /**
  34294. * Returns a normalized vector (Vector3) orthogonal to the ground
  34295. * at the ground coordinates (x, z) expressed in the World system.
  34296. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34297. * Not pertinent if the ground is rotated.
  34298. */
  34299. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34300. var normal = new BABYLON.Vector3(0, 1, 0);
  34301. this.getNormalAtCoordinatesToRef(x, z, normal);
  34302. return normal;
  34303. };
  34304. /**
  34305. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34306. * at the ground coordinates (x, z) expressed in the World system.
  34307. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34308. * Not pertinent if the ground is rotated.
  34309. */
  34310. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34311. // express x and y in the ground local system
  34312. x -= this.position.x;
  34313. z -= this.position.z;
  34314. x /= this.scaling.x;
  34315. z /= this.scaling.z;
  34316. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34317. return;
  34318. }
  34319. if (!this._heightQuads || this._heightQuads.length == 0) {
  34320. this._initHeightQuads();
  34321. this._computeHeightQuads();
  34322. }
  34323. var facet = this._getFacetAt(x, z);
  34324. ref.x = facet.x;
  34325. ref.y = facet.y;
  34326. ref.z = facet.z;
  34327. };
  34328. /**
  34329. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34330. * if the ground has been updated.
  34331. * This can be used in the render loop
  34332. */
  34333. GroundMesh.prototype.updateCoordinateHeights = function () {
  34334. if (!this._heightQuads || this._heightQuads.length == 0) {
  34335. this._initHeightQuads();
  34336. }
  34337. this._computeHeightQuads();
  34338. };
  34339. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34340. GroundMesh.prototype._getFacetAt = function (x, z) {
  34341. // retrieve col and row from x, z coordinates in the ground local system
  34342. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34343. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34344. var quad = this._heightQuads[row * this._subdivisions + col];
  34345. var facet;
  34346. if (z < quad.slope.x * x + quad.slope.y) {
  34347. facet = quad.facet1;
  34348. }
  34349. else {
  34350. facet = quad.facet2;
  34351. }
  34352. return facet;
  34353. };
  34354. // Creates and populates the heightMap array with "facet" elements :
  34355. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34356. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34357. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34358. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34359. GroundMesh.prototype._initHeightQuads = function () {
  34360. this._heightQuads = new Array();
  34361. for (var row = 0; row < this._subdivisions; row++) {
  34362. for (var col = 0; col < this._subdivisions; col++) {
  34363. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34364. this._heightQuads[row * this._subdivisions + col] = quad;
  34365. }
  34366. }
  34367. };
  34368. // Compute each quad element values and update the the heightMap array :
  34369. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34370. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34371. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34372. GroundMesh.prototype._computeHeightQuads = function () {
  34373. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34374. var v1 = BABYLON.Tmp.Vector3[3];
  34375. var v2 = BABYLON.Tmp.Vector3[2];
  34376. var v3 = BABYLON.Tmp.Vector3[1];
  34377. var v4 = BABYLON.Tmp.Vector3[0];
  34378. var v1v2 = BABYLON.Tmp.Vector3[4];
  34379. var v1v3 = BABYLON.Tmp.Vector3[5];
  34380. var v1v4 = BABYLON.Tmp.Vector3[6];
  34381. var norm1 = BABYLON.Tmp.Vector3[7];
  34382. var norm2 = BABYLON.Tmp.Vector3[8];
  34383. var i = 0;
  34384. var j = 0;
  34385. var k = 0;
  34386. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34387. var h = 0;
  34388. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34389. var d2 = 0;
  34390. for (var row = 0; row < this._subdivisions; row++) {
  34391. for (var col = 0; col < this._subdivisions; col++) {
  34392. i = col * 3;
  34393. j = row * (this._subdivisions + 1) * 3;
  34394. k = (row + 1) * (this._subdivisions + 1) * 3;
  34395. v1.x = positions[j + i];
  34396. v1.y = positions[j + i + 1];
  34397. v1.z = positions[j + i + 2];
  34398. v2.x = positions[j + i + 3];
  34399. v2.y = positions[j + i + 4];
  34400. v2.z = positions[j + i + 5];
  34401. v3.x = positions[k + i];
  34402. v3.y = positions[k + i + 1];
  34403. v3.z = positions[k + i + 2];
  34404. v4.x = positions[k + i + 3];
  34405. v4.y = positions[k + i + 4];
  34406. v4.z = positions[k + i + 5];
  34407. // 2D slope V1V4
  34408. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34409. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34410. // facet equations :
  34411. // we compute each facet normal vector
  34412. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34413. // we compute the value d by applying the equation to v1 which belongs to the plane
  34414. // then we store the facet equation in a Vector4
  34415. v2.subtractToRef(v1, v1v2);
  34416. v3.subtractToRef(v1, v1v3);
  34417. v4.subtractToRef(v1, v1v4);
  34418. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34419. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34420. norm1.normalize();
  34421. norm2.normalize();
  34422. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34423. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34424. var quad = this._heightQuads[row * this._subdivisions + col];
  34425. quad.slope.copyFromFloats(cd, h);
  34426. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34427. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34428. }
  34429. }
  34430. };
  34431. return GroundMesh;
  34432. })(BABYLON.Mesh);
  34433. BABYLON.GroundMesh = GroundMesh;
  34434. })(BABYLON || (BABYLON = {}));
  34435. var BABYLON;
  34436. (function (BABYLON) {
  34437. var LinesMesh = (function (_super) {
  34438. __extends(LinesMesh, _super);
  34439. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  34440. if (parent === void 0) { parent = null; }
  34441. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  34442. this.color = new BABYLON.Color3(1, 1, 1);
  34443. this.alpha = 1;
  34444. this._positionBuffer = {};
  34445. if (source) {
  34446. this.color = source.color.clone();
  34447. this.alpha = source.alpha;
  34448. }
  34449. this._intersectionThreshold = 0.1;
  34450. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  34451. attributes: [BABYLON.VertexBuffer.PositionKind],
  34452. uniforms: ["worldViewProjection", "color"],
  34453. needAlphaBlending: true
  34454. });
  34455. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  34456. }
  34457. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34458. /**
  34459. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34460. * This margin is expressed in world space coordinates, so its value may vary.
  34461. * Default value is 0.1
  34462. * @returns the intersection Threshold value.
  34463. */
  34464. get: function () {
  34465. return this._intersectionThreshold;
  34466. },
  34467. /**
  34468. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34469. * This margin is expressed in world space coordinates, so its value may vary.
  34470. * @param value the new threshold to apply
  34471. */
  34472. set: function (value) {
  34473. if (this._intersectionThreshold === value) {
  34474. return;
  34475. }
  34476. this._intersectionThreshold = value;
  34477. if (this.geometry) {
  34478. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34479. }
  34480. },
  34481. enumerable: true,
  34482. configurable: true
  34483. });
  34484. Object.defineProperty(LinesMesh.prototype, "material", {
  34485. get: function () {
  34486. return this._colorShader;
  34487. },
  34488. enumerable: true,
  34489. configurable: true
  34490. });
  34491. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34492. get: function () {
  34493. return false;
  34494. },
  34495. enumerable: true,
  34496. configurable: true
  34497. });
  34498. LinesMesh.prototype.createInstance = function (name) {
  34499. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34500. return null;
  34501. };
  34502. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34503. var engine = this.getScene().getEngine();
  34504. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  34505. // VBOs
  34506. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  34507. // Color
  34508. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34509. };
  34510. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34511. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34512. return;
  34513. }
  34514. var engine = this.getScene().getEngine();
  34515. // Draw order
  34516. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34517. };
  34518. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34519. this._colorShader.dispose();
  34520. _super.prototype.dispose.call(this, doNotRecurse);
  34521. };
  34522. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34523. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34524. };
  34525. return LinesMesh;
  34526. })(BABYLON.Mesh);
  34527. BABYLON.LinesMesh = LinesMesh;
  34528. })(BABYLON || (BABYLON = {}));
  34529. var BABYLON;
  34530. (function (BABYLON) {
  34531. var DefaultLoadingScreen = (function () {
  34532. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  34533. var _this = this;
  34534. if (_loadingText === void 0) { _loadingText = ""; }
  34535. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  34536. this._renderingCanvas = _renderingCanvas;
  34537. this._loadingText = _loadingText;
  34538. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  34539. // Resize
  34540. this._resizeLoadingUI = function () {
  34541. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  34542. _this._loadingDiv.style.position = "absolute";
  34543. _this._loadingDiv.style.left = canvasRect.left + "px";
  34544. _this._loadingDiv.style.top = canvasRect.top + "px";
  34545. _this._loadingDiv.style.width = canvasRect.width + "px";
  34546. _this._loadingDiv.style.height = canvasRect.height + "px";
  34547. };
  34548. }
  34549. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  34550. var _this = this;
  34551. if (this._loadingDiv) {
  34552. // Do not add a loading screen if there is already one
  34553. return;
  34554. }
  34555. this._loadingDiv = document.createElement("div");
  34556. this._loadingDiv.id = "babylonjsLoadingDiv";
  34557. this._loadingDiv.style.opacity = "0";
  34558. this._loadingDiv.style.transition = "opacity 1.5s ease";
  34559. // Loading text
  34560. this._loadingTextDiv = document.createElement("div");
  34561. this._loadingTextDiv.style.position = "absolute";
  34562. this._loadingTextDiv.style.left = "0";
  34563. this._loadingTextDiv.style.top = "50%";
  34564. this._loadingTextDiv.style.marginTop = "80px";
  34565. this._loadingTextDiv.style.width = "100%";
  34566. this._loadingTextDiv.style.height = "20px";
  34567. this._loadingTextDiv.style.fontFamily = "Arial";
  34568. this._loadingTextDiv.style.fontSize = "14px";
  34569. this._loadingTextDiv.style.color = "white";
  34570. this._loadingTextDiv.style.textAlign = "center";
  34571. this._loadingTextDiv.innerHTML = "Loading";
  34572. this._loadingDiv.appendChild(this._loadingTextDiv);
  34573. //set the predefined text
  34574. this._loadingTextDiv.innerHTML = this._loadingText;
  34575. // Loading img
  34576. var imgBack = new Image();
  34577. 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==";
  34578. imgBack.style.position = "absolute";
  34579. imgBack.style.left = "50%";
  34580. imgBack.style.top = "50%";
  34581. imgBack.style.marginLeft = "-50px";
  34582. imgBack.style.marginTop = "-50px";
  34583. imgBack.style.transition = "transform 1.0s ease";
  34584. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  34585. var deg = 360;
  34586. var onTransitionEnd = function () {
  34587. deg += 360;
  34588. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  34589. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  34590. };
  34591. imgBack.addEventListener("transitionend", onTransitionEnd);
  34592. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  34593. this._loadingDiv.appendChild(imgBack);
  34594. // front image
  34595. var imgFront = new Image();
  34596. 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=";
  34597. imgFront.style.position = "absolute";
  34598. imgFront.style.left = "50%";
  34599. imgFront.style.top = "50%";
  34600. imgFront.style.marginLeft = "-50px";
  34601. imgFront.style.marginTop = "-50px";
  34602. this._loadingDiv.appendChild(imgFront);
  34603. this._resizeLoadingUI();
  34604. window.addEventListener("resize", this._resizeLoadingUI);
  34605. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34606. document.body.appendChild(this._loadingDiv);
  34607. setTimeout(function () {
  34608. _this._loadingDiv.style.opacity = "1";
  34609. imgBack.style.transform = "rotateZ(360deg)";
  34610. imgBack.style.webkitTransform = "rotateZ(360deg)";
  34611. }, 0);
  34612. };
  34613. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  34614. var _this = this;
  34615. if (!this._loadingDiv) {
  34616. return;
  34617. }
  34618. var onTransitionEnd = function () {
  34619. if (!_this._loadingDiv) {
  34620. return;
  34621. }
  34622. document.body.removeChild(_this._loadingDiv);
  34623. window.removeEventListener("resize", _this._resizeLoadingUI);
  34624. _this._loadingDiv = null;
  34625. };
  34626. this._loadingDiv.style.opacity = "0";
  34627. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  34628. };
  34629. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  34630. set: function (text) {
  34631. this._loadingText = text;
  34632. if (this._loadingTextDiv) {
  34633. this._loadingTextDiv.innerHTML = this._loadingText;
  34634. }
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  34640. get: function () {
  34641. return this._loadingDivBackgroundColor;
  34642. },
  34643. set: function (color) {
  34644. this._loadingDivBackgroundColor = color;
  34645. if (!this._loadingDiv) {
  34646. return;
  34647. }
  34648. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. return DefaultLoadingScreen;
  34654. })();
  34655. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  34656. })(BABYLON || (BABYLON = {}));
  34657. var BABYLON;
  34658. (function (BABYLON) {
  34659. var AudioEngine = (function () {
  34660. function AudioEngine() {
  34661. this._audioContext = null;
  34662. this._audioContextInitialized = false;
  34663. this.canUseWebAudio = false;
  34664. this.WarnedWebAudioUnsupported = false;
  34665. this.unlocked = false;
  34666. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  34667. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  34668. this.canUseWebAudio = true;
  34669. }
  34670. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  34671. this._unlockiOSaudio();
  34672. }
  34673. else {
  34674. this.unlocked = true;
  34675. }
  34676. }
  34677. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  34678. get: function () {
  34679. if (!this._audioContextInitialized) {
  34680. this._initializeAudioContext();
  34681. }
  34682. return this._audioContext;
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. AudioEngine.prototype._unlockiOSaudio = function () {
  34688. var _this = this;
  34689. var unlockaudio = function () {
  34690. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  34691. var source = _this.audioContext.createBufferSource();
  34692. source.buffer = buffer;
  34693. source.connect(_this.audioContext.destination);
  34694. source.start(0);
  34695. setTimeout(function () {
  34696. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  34697. _this.unlocked = true;
  34698. window.removeEventListener('touchend', unlockaudio, false);
  34699. if (_this.onAudioUnlocked) {
  34700. _this.onAudioUnlocked();
  34701. }
  34702. }
  34703. }, 0);
  34704. };
  34705. window.addEventListener('touchend', unlockaudio, false);
  34706. };
  34707. AudioEngine.prototype._initializeAudioContext = function () {
  34708. try {
  34709. if (this.canUseWebAudio) {
  34710. this._audioContext = new AudioContext();
  34711. // create a global volume gain node
  34712. this.masterGain = this._audioContext.createGain();
  34713. this.masterGain.gain.value = 1;
  34714. this.masterGain.connect(this._audioContext.destination);
  34715. this._audioContextInitialized = true;
  34716. }
  34717. }
  34718. catch (e) {
  34719. this.canUseWebAudio = false;
  34720. BABYLON.Tools.Error("Web Audio: " + e.message);
  34721. }
  34722. };
  34723. AudioEngine.prototype.dispose = function () {
  34724. if (this.canUseWebAudio && this._audioContextInitialized) {
  34725. if (this._connectedAnalyser) {
  34726. this._connectedAnalyser.stopDebugCanvas();
  34727. this._connectedAnalyser.dispose();
  34728. this.masterGain.disconnect();
  34729. this.masterGain.connect(this._audioContext.destination);
  34730. this._connectedAnalyser = null;
  34731. }
  34732. this.masterGain.gain.value = 1;
  34733. }
  34734. this.WarnedWebAudioUnsupported = false;
  34735. };
  34736. AudioEngine.prototype.getGlobalVolume = function () {
  34737. if (this.canUseWebAudio && this._audioContextInitialized) {
  34738. return this.masterGain.gain.value;
  34739. }
  34740. else {
  34741. return -1;
  34742. }
  34743. };
  34744. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  34745. if (this.canUseWebAudio && this._audioContextInitialized) {
  34746. this.masterGain.gain.value = newVolume;
  34747. }
  34748. };
  34749. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  34750. if (this._connectedAnalyser) {
  34751. this._connectedAnalyser.stopDebugCanvas();
  34752. }
  34753. if (this.canUseWebAudio && this._audioContextInitialized) {
  34754. this._connectedAnalyser = analyser;
  34755. this.masterGain.disconnect();
  34756. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  34757. }
  34758. };
  34759. return AudioEngine;
  34760. })();
  34761. BABYLON.AudioEngine = AudioEngine;
  34762. })(BABYLON || (BABYLON = {}));
  34763. var BABYLON;
  34764. (function (BABYLON) {
  34765. var Sound = (function () {
  34766. /**
  34767. * Create a sound and attach it to a scene
  34768. * @param name Name of your sound
  34769. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  34770. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  34771. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  34772. */
  34773. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  34774. var _this = this;
  34775. this.autoplay = false;
  34776. this.loop = false;
  34777. this.useCustomAttenuation = false;
  34778. this.spatialSound = false;
  34779. this.refDistance = 1;
  34780. this.rolloffFactor = 1;
  34781. this.maxDistance = 100;
  34782. this.distanceModel = "linear";
  34783. this._panningModel = "equalpower";
  34784. this._playbackRate = 1;
  34785. this._streaming = false;
  34786. this._startTime = 0;
  34787. this._startOffset = 0;
  34788. this._position = BABYLON.Vector3.Zero();
  34789. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  34790. this._volume = 1;
  34791. this._isLoaded = false;
  34792. this._isReadyToPlay = false;
  34793. this.isPlaying = false;
  34794. this.isPaused = false;
  34795. this._isDirectional = false;
  34796. // Used if you'd like to create a directional sound.
  34797. // If not set, the sound will be omnidirectional
  34798. this._coneInnerAngle = 360;
  34799. this._coneOuterAngle = 360;
  34800. this._coneOuterGain = 0;
  34801. this._isOutputConnected = false;
  34802. this.name = name;
  34803. this._scene = scene;
  34804. this._readyToPlayCallback = readyToPlayCallback;
  34805. // Default custom attenuation function is a linear attenuation
  34806. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  34807. if (currentDistance < maxDistance) {
  34808. return currentVolume * (1 - currentDistance / maxDistance);
  34809. }
  34810. else {
  34811. return 0;
  34812. }
  34813. };
  34814. if (options) {
  34815. this.autoplay = options.autoplay || false;
  34816. this.loop = options.loop || false;
  34817. // if volume === 0, we need another way to check this option
  34818. if (options.volume !== undefined) {
  34819. this._volume = options.volume;
  34820. }
  34821. this.spatialSound = options.spatialSound || false;
  34822. this.maxDistance = options.maxDistance || 100;
  34823. this.useCustomAttenuation = options.useCustomAttenuation || false;
  34824. this.rolloffFactor = options.rolloffFactor || 1;
  34825. this.refDistance = options.refDistance || 1;
  34826. this.distanceModel = options.distanceModel || "linear";
  34827. this._playbackRate = options.playbackRate || 1;
  34828. this._streaming = options.streaming || false;
  34829. }
  34830. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34831. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  34832. this._soundGain.gain.value = this._volume;
  34833. this._inputAudioNode = this._soundGain;
  34834. this._ouputAudioNode = this._soundGain;
  34835. if (this.spatialSound) {
  34836. this._createSpatialParameters();
  34837. }
  34838. this._scene.mainSoundTrack.AddSound(this);
  34839. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  34840. if (urlOrArrayBuffer) {
  34841. // If it's an URL
  34842. if (typeof (urlOrArrayBuffer) === "string") {
  34843. // Loading sound using XHR2
  34844. if (!this._streaming) {
  34845. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  34846. }
  34847. else {
  34848. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  34849. this._htmlAudioElement.controls = false;
  34850. this._htmlAudioElement.loop = this.loop;
  34851. this._htmlAudioElement.crossOrigin = "anonymous";
  34852. this._htmlAudioElement.preload = "auto";
  34853. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  34854. _this._isReadyToPlay = true;
  34855. if (_this.autoplay) {
  34856. _this.play();
  34857. }
  34858. if (_this._readyToPlayCallback) {
  34859. _this._readyToPlayCallback();
  34860. }
  34861. });
  34862. document.body.appendChild(this._htmlAudioElement);
  34863. }
  34864. }
  34865. else {
  34866. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  34867. if (urlOrArrayBuffer.byteLength > 0) {
  34868. this._soundLoaded(urlOrArrayBuffer);
  34869. }
  34870. }
  34871. else {
  34872. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  34873. }
  34874. }
  34875. }
  34876. }
  34877. else {
  34878. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  34879. this._scene.mainSoundTrack.AddSound(this);
  34880. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  34881. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  34882. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  34883. }
  34884. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  34885. if (this._readyToPlayCallback) {
  34886. window.setTimeout(function () {
  34887. _this._readyToPlayCallback();
  34888. }, 1000);
  34889. }
  34890. }
  34891. }
  34892. Sound.prototype.dispose = function () {
  34893. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  34894. if (this.isPlaying) {
  34895. this.stop();
  34896. }
  34897. this._isReadyToPlay = false;
  34898. if (this.soundTrackId === -1) {
  34899. this._scene.mainSoundTrack.RemoveSound(this);
  34900. }
  34901. else {
  34902. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  34903. }
  34904. if (this._soundGain) {
  34905. this._soundGain.disconnect();
  34906. this._soundGain = null;
  34907. }
  34908. if (this._soundPanner) {
  34909. this._soundPanner.disconnect();
  34910. this._soundPanner = null;
  34911. }
  34912. if (this._soundSource) {
  34913. this._soundSource.disconnect();
  34914. this._soundSource = null;
  34915. }
  34916. this._audioBuffer = null;
  34917. if (this._htmlAudioElement) {
  34918. this._htmlAudioElement.pause();
  34919. this._htmlAudioElement.src = "";
  34920. document.body.removeChild(this._htmlAudioElement);
  34921. }
  34922. if (this._connectedMesh) {
  34923. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34924. this._connectedMesh = null;
  34925. }
  34926. }
  34927. };
  34928. Sound.prototype._soundLoaded = function (audioData) {
  34929. var _this = this;
  34930. this._isLoaded = true;
  34931. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  34932. _this._audioBuffer = buffer;
  34933. _this._isReadyToPlay = true;
  34934. if (_this.autoplay) {
  34935. _this.play();
  34936. }
  34937. if (_this._readyToPlayCallback) {
  34938. _this._readyToPlayCallback();
  34939. }
  34940. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  34941. };
  34942. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  34943. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34944. this._audioBuffer = audioBuffer;
  34945. this._isReadyToPlay = true;
  34946. }
  34947. };
  34948. Sound.prototype.updateOptions = function (options) {
  34949. if (options) {
  34950. this.loop = options.loop || this.loop;
  34951. this.maxDistance = options.maxDistance || this.maxDistance;
  34952. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  34953. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  34954. this.refDistance = options.refDistance || this.refDistance;
  34955. this.distanceModel = options.distanceModel || this.distanceModel;
  34956. this._playbackRate = options.playbackRate || this._playbackRate;
  34957. this._updateSpatialParameters();
  34958. if (this.isPlaying) {
  34959. if (this._streaming) {
  34960. this._htmlAudioElement.playbackRate = this._playbackRate;
  34961. }
  34962. else {
  34963. this._soundSource.playbackRate.value = this._playbackRate;
  34964. }
  34965. }
  34966. }
  34967. };
  34968. Sound.prototype._createSpatialParameters = function () {
  34969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34970. if (this._scene.headphone) {
  34971. this._panningModel = "HRTF";
  34972. }
  34973. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  34974. this._updateSpatialParameters();
  34975. this._soundPanner.connect(this._ouputAudioNode);
  34976. this._inputAudioNode = this._soundPanner;
  34977. }
  34978. };
  34979. Sound.prototype._updateSpatialParameters = function () {
  34980. if (this.spatialSound) {
  34981. if (this.useCustomAttenuation) {
  34982. // Tricks to disable in a way embedded Web Audio attenuation
  34983. this._soundPanner.distanceModel = "linear";
  34984. this._soundPanner.maxDistance = Number.MAX_VALUE;
  34985. this._soundPanner.refDistance = 1;
  34986. this._soundPanner.rolloffFactor = 1;
  34987. this._soundPanner.panningModel = this._panningModel;
  34988. }
  34989. else {
  34990. this._soundPanner.distanceModel = this.distanceModel;
  34991. this._soundPanner.maxDistance = this.maxDistance;
  34992. this._soundPanner.refDistance = this.refDistance;
  34993. this._soundPanner.rolloffFactor = this.rolloffFactor;
  34994. this._soundPanner.panningModel = this._panningModel;
  34995. }
  34996. }
  34997. };
  34998. Sound.prototype.switchPanningModelToHRTF = function () {
  34999. this._panningModel = "HRTF";
  35000. this._switchPanningModel();
  35001. };
  35002. Sound.prototype.switchPanningModelToEqualPower = function () {
  35003. this._panningModel = "equalpower";
  35004. this._switchPanningModel();
  35005. };
  35006. Sound.prototype._switchPanningModel = function () {
  35007. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35008. this._soundPanner.panningModel = this._panningModel;
  35009. }
  35010. };
  35011. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35012. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35013. if (this._isOutputConnected) {
  35014. this._ouputAudioNode.disconnect();
  35015. }
  35016. this._ouputAudioNode.connect(soundTrackAudioNode);
  35017. this._isOutputConnected = true;
  35018. }
  35019. };
  35020. /**
  35021. * Transform this sound into a directional source
  35022. * @param coneInnerAngle Size of the inner cone in degree
  35023. * @param coneOuterAngle Size of the outer cone in degree
  35024. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35025. */
  35026. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35027. if (coneOuterAngle < coneInnerAngle) {
  35028. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35029. return;
  35030. }
  35031. this._coneInnerAngle = coneInnerAngle;
  35032. this._coneOuterAngle = coneOuterAngle;
  35033. this._coneOuterGain = coneOuterGain;
  35034. this._isDirectional = true;
  35035. if (this.isPlaying && this.loop) {
  35036. this.stop();
  35037. this.play();
  35038. }
  35039. };
  35040. Sound.prototype.setPosition = function (newPosition) {
  35041. this._position = newPosition;
  35042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35043. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35044. }
  35045. };
  35046. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35047. this._localDirection = newLocalDirection;
  35048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35049. this._updateDirection();
  35050. }
  35051. };
  35052. Sound.prototype._updateDirection = function () {
  35053. var mat = this._connectedMesh.getWorldMatrix();
  35054. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35055. direction.normalize();
  35056. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35057. };
  35058. Sound.prototype.updateDistanceFromListener = function () {
  35059. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35060. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35061. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35062. }
  35063. };
  35064. Sound.prototype.setAttenuationFunction = function (callback) {
  35065. this._customAttenuationFunction = callback;
  35066. };
  35067. /**
  35068. * Play the sound
  35069. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35070. * @param offset (optional) Start the sound setting it at a specific time
  35071. */
  35072. Sound.prototype.play = function (time, offset) {
  35073. var _this = this;
  35074. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35075. try {
  35076. if (this._startOffset < 0) {
  35077. time = -this._startOffset;
  35078. this._startOffset = 0;
  35079. }
  35080. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35081. if (!this._soundSource || !this._streamingSource) {
  35082. if (this.spatialSound) {
  35083. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35084. if (this._isDirectional) {
  35085. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35086. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35087. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35088. if (this._connectedMesh) {
  35089. this._updateDirection();
  35090. }
  35091. else {
  35092. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35093. }
  35094. }
  35095. }
  35096. }
  35097. if (this._streaming) {
  35098. if (!this._streamingSource) {
  35099. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35100. this._htmlAudioElement.onended = function () { _this._onended(); };
  35101. this._htmlAudioElement.playbackRate = this._playbackRate;
  35102. }
  35103. this._streamingSource.disconnect();
  35104. this._streamingSource.connect(this._inputAudioNode);
  35105. this._htmlAudioElement.play();
  35106. }
  35107. else {
  35108. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35109. this._soundSource.buffer = this._audioBuffer;
  35110. this._soundSource.connect(this._inputAudioNode);
  35111. this._soundSource.loop = this.loop;
  35112. this._soundSource.playbackRate.value = this._playbackRate;
  35113. this._soundSource.onended = function () { _this._onended(); };
  35114. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35115. }
  35116. this._startTime = startTime;
  35117. this.isPlaying = true;
  35118. this.isPaused = false;
  35119. }
  35120. catch (ex) {
  35121. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35122. }
  35123. }
  35124. };
  35125. Sound.prototype._onended = function () {
  35126. this.isPlaying = false;
  35127. if (this.onended) {
  35128. this.onended();
  35129. }
  35130. };
  35131. /**
  35132. * Stop the sound
  35133. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35134. */
  35135. Sound.prototype.stop = function (time) {
  35136. if (this.isPlaying) {
  35137. if (this._streaming) {
  35138. this._htmlAudioElement.pause();
  35139. // Test needed for Firefox or it will generate an Invalid State Error
  35140. if (this._htmlAudioElement.currentTime > 0) {
  35141. this._htmlAudioElement.currentTime = 0;
  35142. }
  35143. }
  35144. else {
  35145. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35146. this._soundSource.stop(stopTime);
  35147. this._soundSource.onended = null;
  35148. if (!this.isPaused) {
  35149. this._startOffset = 0;
  35150. }
  35151. }
  35152. this.isPlaying = false;
  35153. }
  35154. };
  35155. Sound.prototype.pause = function () {
  35156. if (this.isPlaying) {
  35157. this.isPaused = true;
  35158. if (this._streaming) {
  35159. this._htmlAudioElement.pause();
  35160. }
  35161. else {
  35162. this.stop(0);
  35163. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35164. }
  35165. }
  35166. };
  35167. Sound.prototype.setVolume = function (newVolume, time) {
  35168. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35169. if (time) {
  35170. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35171. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35172. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35173. }
  35174. else {
  35175. this._soundGain.gain.value = newVolume;
  35176. }
  35177. }
  35178. this._volume = newVolume;
  35179. };
  35180. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35181. this._playbackRate = newPlaybackRate;
  35182. if (this.isPlaying) {
  35183. if (this._streaming) {
  35184. this._htmlAudioElement.playbackRate = this._playbackRate;
  35185. }
  35186. else {
  35187. this._soundSource.playbackRate.value = this._playbackRate;
  35188. }
  35189. }
  35190. };
  35191. Sound.prototype.getVolume = function () {
  35192. return this._volume;
  35193. };
  35194. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35195. var _this = this;
  35196. if (this._connectedMesh) {
  35197. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35198. this._registerFunc = null;
  35199. }
  35200. this._connectedMesh = meshToConnectTo;
  35201. if (!this.spatialSound) {
  35202. this.spatialSound = true;
  35203. this._createSpatialParameters();
  35204. if (this.isPlaying && this.loop) {
  35205. this.stop();
  35206. this.play();
  35207. }
  35208. }
  35209. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35210. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35211. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35212. };
  35213. Sound.prototype.detachFromMesh = function () {
  35214. if (this._connectedMesh) {
  35215. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35216. this._registerFunc = null;
  35217. this._connectedMesh = null;
  35218. }
  35219. };
  35220. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35221. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35222. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35223. this._updateDirection();
  35224. }
  35225. };
  35226. Sound.prototype.clone = function () {
  35227. var _this = this;
  35228. if (!this._streaming) {
  35229. var setBufferAndRun = function () {
  35230. if (_this._isReadyToPlay) {
  35231. clonedSound._audioBuffer = _this.getAudioBuffer();
  35232. clonedSound._isReadyToPlay = true;
  35233. if (clonedSound.autoplay) {
  35234. clonedSound.play();
  35235. }
  35236. }
  35237. else {
  35238. window.setTimeout(setBufferAndRun, 300);
  35239. }
  35240. };
  35241. var currentOptions = {
  35242. autoplay: this.autoplay, loop: this.loop,
  35243. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35244. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35245. refDistance: this.refDistance, distanceModel: this.distanceModel
  35246. };
  35247. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35248. if (this.useCustomAttenuation) {
  35249. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35250. }
  35251. clonedSound.setPosition(this._position);
  35252. clonedSound.setPlaybackRate(this._playbackRate);
  35253. setBufferAndRun();
  35254. return clonedSound;
  35255. }
  35256. else {
  35257. return null;
  35258. }
  35259. };
  35260. Sound.prototype.getAudioBuffer = function () {
  35261. return this._audioBuffer;
  35262. };
  35263. Sound.prototype.serialize = function () {
  35264. var serializationObject = {
  35265. name: this.name,
  35266. url: this.name,
  35267. autoplay: this.autoplay,
  35268. loop: this.loop,
  35269. volume: this._volume,
  35270. spatialSound: this.spatialSound,
  35271. maxDistance: this.maxDistance,
  35272. rolloffFactor: this.rolloffFactor,
  35273. refDistance: this.refDistance,
  35274. distanceModel: this.distanceModel,
  35275. playbackRate: this._playbackRate,
  35276. panningModel: this._panningModel,
  35277. soundTrackId: this.soundTrackId
  35278. };
  35279. if (this.spatialSound) {
  35280. if (this._connectedMesh)
  35281. serializationObject.connectedMeshId = this._connectedMesh.id;
  35282. serializationObject.position = this._position.asArray();
  35283. serializationObject.refDistance = this.refDistance;
  35284. serializationObject.distanceModel = this.distanceModel;
  35285. serializationObject.isDirectional = this._isDirectional;
  35286. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35287. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35288. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35289. serializationObject.coneOuterGain = this._coneOuterGain;
  35290. }
  35291. return serializationObject;
  35292. };
  35293. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35294. var soundName = parsedSound.name;
  35295. var soundUrl;
  35296. if (parsedSound.url) {
  35297. soundUrl = rootUrl + parsedSound.url;
  35298. }
  35299. else {
  35300. soundUrl = rootUrl + soundName;
  35301. }
  35302. var options = {
  35303. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35304. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35305. rolloffFactor: parsedSound.rolloffFactor,
  35306. refDistance: parsedSound.refDistance,
  35307. distanceModel: parsedSound.distanceModel,
  35308. playbackRate: parsedSound.playbackRate
  35309. };
  35310. var newSound;
  35311. if (!sourceSound) {
  35312. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35313. scene._addPendingData(newSound);
  35314. }
  35315. else {
  35316. var setBufferAndRun = function () {
  35317. if (sourceSound._isReadyToPlay) {
  35318. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35319. newSound._isReadyToPlay = true;
  35320. if (newSound.autoplay) {
  35321. newSound.play();
  35322. }
  35323. }
  35324. else {
  35325. window.setTimeout(setBufferAndRun, 300);
  35326. }
  35327. };
  35328. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35329. setBufferAndRun();
  35330. }
  35331. if (parsedSound.position) {
  35332. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35333. newSound.setPosition(soundPosition);
  35334. }
  35335. if (parsedSound.isDirectional) {
  35336. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35337. if (parsedSound.localDirectionToMesh) {
  35338. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35339. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35340. }
  35341. }
  35342. if (parsedSound.connectedMeshId) {
  35343. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35344. if (connectedMesh) {
  35345. newSound.attachToMesh(connectedMesh);
  35346. }
  35347. }
  35348. return newSound;
  35349. };
  35350. return Sound;
  35351. })();
  35352. BABYLON.Sound = Sound;
  35353. })(BABYLON || (BABYLON = {}));
  35354. var BABYLON;
  35355. (function (BABYLON) {
  35356. var SoundTrack = (function () {
  35357. function SoundTrack(scene, options) {
  35358. this.id = -1;
  35359. this._isMainTrack = false;
  35360. this._isInitialized = false;
  35361. this._scene = scene;
  35362. this.soundCollection = new Array();
  35363. this._options = options;
  35364. if (!this._isMainTrack) {
  35365. this._scene.soundTracks.push(this);
  35366. this.id = this._scene.soundTracks.length - 1;
  35367. }
  35368. }
  35369. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  35370. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35371. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  35372. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  35373. if (this._options) {
  35374. if (this._options.volume) {
  35375. this._outputAudioNode.gain.value = this._options.volume;
  35376. }
  35377. if (this._options.mainTrack) {
  35378. this._isMainTrack = this._options.mainTrack;
  35379. }
  35380. }
  35381. this._isInitialized = true;
  35382. }
  35383. };
  35384. SoundTrack.prototype.dispose = function () {
  35385. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35386. if (this._connectedAnalyser) {
  35387. this._connectedAnalyser.stopDebugCanvas();
  35388. }
  35389. while (this.soundCollection.length) {
  35390. this.soundCollection[0].dispose();
  35391. }
  35392. if (this._outputAudioNode) {
  35393. this._outputAudioNode.disconnect();
  35394. }
  35395. this._outputAudioNode = null;
  35396. }
  35397. };
  35398. SoundTrack.prototype.AddSound = function (sound) {
  35399. if (!this._isInitialized) {
  35400. this._initializeSoundTrackAudioGraph();
  35401. }
  35402. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35403. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  35404. }
  35405. if (sound.soundTrackId) {
  35406. if (sound.soundTrackId === -1) {
  35407. this._scene.mainSoundTrack.RemoveSound(sound);
  35408. }
  35409. else {
  35410. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  35411. }
  35412. }
  35413. this.soundCollection.push(sound);
  35414. sound.soundTrackId = this.id;
  35415. };
  35416. SoundTrack.prototype.RemoveSound = function (sound) {
  35417. var index = this.soundCollection.indexOf(sound);
  35418. if (index !== -1) {
  35419. this.soundCollection.splice(index, 1);
  35420. }
  35421. };
  35422. SoundTrack.prototype.setVolume = function (newVolume) {
  35423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35424. this._outputAudioNode.gain.value = newVolume;
  35425. }
  35426. };
  35427. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  35428. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35429. for (var i = 0; i < this.soundCollection.length; i++) {
  35430. this.soundCollection[i].switchPanningModelToHRTF();
  35431. }
  35432. }
  35433. };
  35434. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  35435. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35436. for (var i = 0; i < this.soundCollection.length; i++) {
  35437. this.soundCollection[i].switchPanningModelToEqualPower();
  35438. }
  35439. }
  35440. };
  35441. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  35442. if (this._connectedAnalyser) {
  35443. this._connectedAnalyser.stopDebugCanvas();
  35444. }
  35445. this._connectedAnalyser = analyser;
  35446. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35447. this._outputAudioNode.disconnect();
  35448. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  35449. }
  35450. };
  35451. return SoundTrack;
  35452. })();
  35453. BABYLON.SoundTrack = SoundTrack;
  35454. })(BABYLON || (BABYLON = {}));
  35455. var BABYLON;
  35456. (function (BABYLON) {
  35457. var SIMDVector3 = (function () {
  35458. function SIMDVector3() {
  35459. }
  35460. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  35461. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  35462. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35463. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35464. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35465. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35466. 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));
  35467. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35468. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35469. };
  35470. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  35471. var v0 = SIMD.float32x4.splat(x);
  35472. var v1 = SIMD.float32x4.splat(y);
  35473. var v2 = SIMD.float32x4.splat(z);
  35474. var m0 = SIMD.float32x4.load(transformation.m, 0);
  35475. var m1 = SIMD.float32x4.load(transformation.m, 4);
  35476. var m2 = SIMD.float32x4.load(transformation.m, 8);
  35477. var m3 = SIMD.float32x4.load(transformation.m, 12);
  35478. 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));
  35479. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  35480. SIMD.float32x4.storeXYZ(result._data, 0, r);
  35481. };
  35482. return SIMDVector3;
  35483. })();
  35484. BABYLON.SIMDVector3 = SIMDVector3;
  35485. var SIMDMatrix = (function () {
  35486. function SIMDMatrix() {
  35487. }
  35488. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  35489. if (offset === void 0) { offset = 0; }
  35490. var tm = this.m;
  35491. var om = other.m;
  35492. var om0 = SIMD.float32x4.load(om, 0);
  35493. var om1 = SIMD.float32x4.load(om, 4);
  35494. var om2 = SIMD.float32x4.load(om, 8);
  35495. var om3 = SIMD.float32x4.load(om, 12);
  35496. var tm0 = SIMD.float32x4.load(tm, 0);
  35497. 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)))));
  35498. var tm1 = SIMD.float32x4.load(tm, 4);
  35499. 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)))));
  35500. var tm2 = SIMD.float32x4.load(tm, 8);
  35501. 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)))));
  35502. var tm3 = SIMD.float32x4.load(tm, 12);
  35503. 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)))));
  35504. };
  35505. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  35506. var src = this.m;
  35507. var dest = other.m;
  35508. var row0, row1, row2, row3;
  35509. var tmp1;
  35510. var minor0, minor1, minor2, minor3;
  35511. var det;
  35512. // Load the 4 rows
  35513. var src0 = SIMD.float32x4.load(src, 0);
  35514. var src1 = SIMD.float32x4.load(src, 4);
  35515. var src2 = SIMD.float32x4.load(src, 8);
  35516. var src3 = SIMD.float32x4.load(src, 12);
  35517. // Transpose the source matrix. Sort of. Not a true transpose operation
  35518. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35519. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35520. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  35521. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  35522. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35523. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35524. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  35525. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  35526. // This is a true transposition, but it will lead to an incorrect result
  35527. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  35528. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  35529. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35530. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35531. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  35532. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  35533. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  35534. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  35535. // ----
  35536. tmp1 = SIMD.float32x4.mul(row2, row3);
  35537. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35538. minor0 = SIMD.float32x4.mul(row1, tmp1);
  35539. minor1 = SIMD.float32x4.mul(row0, tmp1);
  35540. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35541. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  35542. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  35543. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  35544. // ----
  35545. tmp1 = SIMD.float32x4.mul(row1, row2);
  35546. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35547. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  35548. minor3 = SIMD.float32x4.mul(row0, tmp1);
  35549. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35550. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  35551. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  35552. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  35553. // ----
  35554. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  35555. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35556. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  35557. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  35558. minor2 = SIMD.float32x4.mul(row0, tmp1);
  35559. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35560. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  35561. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  35562. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  35563. // ----
  35564. tmp1 = SIMD.float32x4.mul(row0, row1);
  35565. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35566. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  35567. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  35568. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35569. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  35570. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  35571. // ----
  35572. tmp1 = SIMD.float32x4.mul(row0, row3);
  35573. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35574. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  35575. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  35576. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35577. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  35578. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  35579. // ----
  35580. tmp1 = SIMD.float32x4.mul(row0, row2);
  35581. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  35582. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  35583. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  35584. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  35585. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  35586. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  35587. // Compute determinant
  35588. det = SIMD.float32x4.mul(row0, minor0);
  35589. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  35590. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  35591. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  35592. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  35593. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  35594. // These shuffles aren't necessary if the faulty transposition is done
  35595. // up at the top of this function.
  35596. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  35597. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  35598. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  35599. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  35600. // Compute final values by multiplying with 1/det
  35601. minor0 = SIMD.float32x4.mul(det, minor0);
  35602. minor1 = SIMD.float32x4.mul(det, minor1);
  35603. minor2 = SIMD.float32x4.mul(det, minor2);
  35604. minor3 = SIMD.float32x4.mul(det, minor3);
  35605. SIMD.float32x4.store(dest, 0, minor0);
  35606. SIMD.float32x4.store(dest, 4, minor1);
  35607. SIMD.float32x4.store(dest, 8, minor2);
  35608. SIMD.float32x4.store(dest, 12, minor3);
  35609. return this;
  35610. };
  35611. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  35612. var out = result.m;
  35613. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  35614. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  35615. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  35616. // cc.kmVec3Subtract(f, pCenter, pEye);
  35617. var f = SIMD.float32x4.sub(center, eye);
  35618. // cc.kmVec3Normalize(f, f);
  35619. var tmp = SIMD.float32x4.mul(f, f);
  35620. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35621. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35622. // cc.kmVec3Assign(up, pUp);
  35623. // cc.kmVec3Normalize(up, up);
  35624. tmp = SIMD.float32x4.mul(up, up);
  35625. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35626. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35627. // cc.kmVec3Cross(s, f, up);
  35628. 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)));
  35629. // cc.kmVec3Normalize(s, s);
  35630. tmp = SIMD.float32x4.mul(s, s);
  35631. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35632. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35633. // cc.kmVec3Cross(u, s, f);
  35634. 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)));
  35635. // cc.kmVec3Normalize(s, s);
  35636. tmp = SIMD.float32x4.mul(s, s);
  35637. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  35638. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  35639. var zero = SIMD.float32x4.splat(0.0);
  35640. s = SIMD.float32x4.neg(s);
  35641. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  35642. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  35643. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35644. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  35645. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  35646. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  35647. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  35648. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  35649. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  35650. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  35651. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  35652. var b3 = SIMD.float32x4.neg(eye);
  35653. b3 = SIMD.float32x4.withW(b3, 1.0);
  35654. 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)))));
  35655. 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)))));
  35656. 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)))));
  35657. 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)))));
  35658. };
  35659. return SIMDMatrix;
  35660. })();
  35661. BABYLON.SIMDMatrix = SIMDMatrix;
  35662. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  35663. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  35664. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  35665. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  35666. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  35667. var SIMDHelper = (function () {
  35668. function SIMDHelper() {
  35669. }
  35670. Object.defineProperty(SIMDHelper, "IsEnabled", {
  35671. get: function () {
  35672. return SIMDHelper._isEnabled;
  35673. },
  35674. enumerable: true,
  35675. configurable: true
  35676. });
  35677. SIMDHelper.DisableSIMD = function () {
  35678. // Replace functions
  35679. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  35680. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  35681. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  35682. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  35683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  35684. SIMDHelper._isEnabled = false;
  35685. };
  35686. SIMDHelper.EnableSIMD = function () {
  35687. if (window.SIMD === undefined) {
  35688. return;
  35689. }
  35690. // Replace functions
  35691. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  35692. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  35693. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  35694. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  35695. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  35696. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  35697. get: function () { return this._data[0]; },
  35698. set: function (value) {
  35699. if (!this._data) {
  35700. this._data = new Float32Array(3);
  35701. }
  35702. this._data[0] = value;
  35703. }
  35704. });
  35705. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  35706. get: function () { return this._data[1]; },
  35707. set: function (value) {
  35708. this._data[1] = value;
  35709. }
  35710. });
  35711. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  35712. get: function () { return this._data[2]; },
  35713. set: function (value) {
  35714. this._data[2] = value;
  35715. }
  35716. });
  35717. SIMDHelper._isEnabled = true;
  35718. };
  35719. SIMDHelper._isEnabled = false;
  35720. return SIMDHelper;
  35721. })();
  35722. BABYLON.SIMDHelper = SIMDHelper;
  35723. })(BABYLON || (BABYLON = {}));
  35724. var BABYLON;
  35725. (function (BABYLON) {
  35726. /**
  35727. * This class describe a rectangle that were added to the map.
  35728. * You have access to its coordinates either in pixel or normalized (UV)
  35729. */
  35730. var PackedRect = (function () {
  35731. function PackedRect(root, parent, pos, size) {
  35732. this._pos = pos;
  35733. this._size = size;
  35734. this._root = root;
  35735. this._parent = parent;
  35736. }
  35737. Object.defineProperty(PackedRect.prototype, "pos", {
  35738. /**
  35739. * @returns the position of this node into the map
  35740. */
  35741. get: function () {
  35742. return this._pos;
  35743. },
  35744. enumerable: true,
  35745. configurable: true
  35746. });
  35747. Object.defineProperty(PackedRect.prototype, "contentSize", {
  35748. /**
  35749. * @returns the size of the rectangle this node handles
  35750. */
  35751. get: function () {
  35752. return this._contentSize;
  35753. },
  35754. enumerable: true,
  35755. configurable: true
  35756. });
  35757. Object.defineProperty(PackedRect.prototype, "UVs", {
  35758. /**
  35759. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  35760. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  35761. */
  35762. get: function () {
  35763. return this.getUVsForCustomSize(this._root._size);
  35764. },
  35765. enumerable: true,
  35766. configurable: true
  35767. });
  35768. /**
  35769. * 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.
  35770. * This method will return the UVs for this part by given the custom size of what you really use
  35771. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  35772. */
  35773. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  35774. var mainWidth = this._root._size.width;
  35775. var mainHeight = this._root._size.height;
  35776. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  35777. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  35778. var uvs = new Array();
  35779. uvs.push(topLeft);
  35780. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  35781. uvs.push(rightBottom);
  35782. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  35783. return uvs;
  35784. };
  35785. /**
  35786. * Free this rectangle from the map.
  35787. * Call this method when you no longer need the rectangle to be in the map.
  35788. */
  35789. PackedRect.prototype.freeContent = function () {
  35790. if (!this.contentSize) {
  35791. return;
  35792. }
  35793. this._contentSize = null;
  35794. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  35795. this.attemptDefrag();
  35796. };
  35797. Object.defineProperty(PackedRect.prototype, "isUsed", {
  35798. get: function () {
  35799. return this._contentSize != null || this._leftNode != null;
  35800. },
  35801. enumerable: true,
  35802. configurable: true
  35803. });
  35804. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  35805. var node = this.findNode(contentSize);
  35806. // Not enough space...
  35807. if (!node) {
  35808. return null;
  35809. }
  35810. node.splitNode(contentSize);
  35811. return node;
  35812. };
  35813. PackedRect.prototype.findNode = function (size) {
  35814. var resNode = null;
  35815. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  35816. if (this.isUsed) {
  35817. if (this._leftNode) {
  35818. resNode = this._leftNode.findNode(size);
  35819. }
  35820. if (!resNode && this._rightNode) {
  35821. resNode = this._rightNode.findNode(size);
  35822. }
  35823. if (!resNode && this._bottomNode) {
  35824. resNode = this._bottomNode.findNode(size);
  35825. }
  35826. }
  35827. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  35828. resNode = this;
  35829. }
  35830. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  35831. resNode = this;
  35832. }
  35833. return resNode;
  35834. };
  35835. PackedRect.prototype.splitNode = function (contentSize) {
  35836. // 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)
  35837. if (!this._contentSize && this._initialSize) {
  35838. 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));
  35839. return this._leftNode.splitNode(contentSize);
  35840. }
  35841. else {
  35842. this._contentSize = contentSize.clone();
  35843. this._initialSize = contentSize.clone();
  35844. if (contentSize.width !== this._size.width) {
  35845. 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));
  35846. }
  35847. if (contentSize.height !== this._size.height) {
  35848. 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));
  35849. }
  35850. return this;
  35851. }
  35852. };
  35853. PackedRect.prototype.attemptDefrag = function () {
  35854. if (!this.isUsed && this.isRecursiveFree) {
  35855. this.clearNode();
  35856. if (this._parent) {
  35857. this._parent.attemptDefrag();
  35858. }
  35859. }
  35860. };
  35861. PackedRect.prototype.clearNode = function () {
  35862. this._initialSize = null;
  35863. this._rightNode = null;
  35864. this._bottomNode = null;
  35865. };
  35866. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  35867. get: function () {
  35868. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  35869. },
  35870. enumerable: true,
  35871. configurable: true
  35872. });
  35873. PackedRect.prototype.evalFreeSize = function (size) {
  35874. var levelSize = 0;
  35875. if (!this.isUsed) {
  35876. if (this._initialSize) {
  35877. levelSize = this._initialSize.surface;
  35878. }
  35879. else {
  35880. levelSize = this._size.surface;
  35881. }
  35882. }
  35883. if (this._rightNode) {
  35884. levelSize += this._rightNode.evalFreeSize(0);
  35885. }
  35886. if (this._bottomNode) {
  35887. levelSize += this._bottomNode.evalFreeSize(0);
  35888. }
  35889. return levelSize + size;
  35890. };
  35891. return PackedRect;
  35892. })();
  35893. BABYLON.PackedRect = PackedRect;
  35894. /**
  35895. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  35896. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  35897. * 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.
  35898. */
  35899. var RectPackingMap = (function (_super) {
  35900. __extends(RectPackingMap, _super);
  35901. /**
  35902. * Create an instance of the object with a dimension using the given size
  35903. * @param size The dimension of the rectangle that will contain all the sub ones.
  35904. */
  35905. function RectPackingMap(size) {
  35906. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  35907. this._root = this;
  35908. }
  35909. /**
  35910. * Add a rectangle, finding the best location to store it into the map
  35911. * @param size the dimension of the rectangle to store
  35912. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  35913. */
  35914. RectPackingMap.prototype.addRect = function (size) {
  35915. var node = this.findAndSplitNode(size);
  35916. return node;
  35917. };
  35918. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  35919. /**
  35920. * Return the current space free normalized between [0;1]
  35921. * @returns {}
  35922. */
  35923. get: function () {
  35924. var freeSize = 0;
  35925. freeSize = this.evalFreeSize(freeSize);
  35926. return freeSize / (this._size.width * this._size.height);
  35927. },
  35928. enumerable: true,
  35929. configurable: true
  35930. });
  35931. return RectPackingMap;
  35932. })(PackedRect);
  35933. BABYLON.RectPackingMap = RectPackingMap;
  35934. })(BABYLON || (BABYLON = {}));
  35935. var BABYLON;
  35936. (function (BABYLON) {
  35937. var DynamicFloatArrayElementInfo = (function () {
  35938. function DynamicFloatArrayElementInfo() {
  35939. }
  35940. return DynamicFloatArrayElementInfo;
  35941. })();
  35942. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35943. /**
  35944. * 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.
  35945. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35946. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35947. * 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.
  35948. * 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.
  35949. * 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".
  35950. */
  35951. var DynamicFloatArray = (function () {
  35952. /**
  35953. * Construct an instance of the dynamic float array
  35954. * @param stride size of one element in float (i.e. not bytes!)
  35955. * @param initialElementCount the number of available entries at construction
  35956. */
  35957. function DynamicFloatArray(stride, initialElementCount) {
  35958. this.compareValueOffset = null;
  35959. this.sortingAscending = true;
  35960. this._stride = stride;
  35961. this.buffer = new Float32Array(stride * initialElementCount);
  35962. this._lastUsed = 0;
  35963. this._firstFree = 0;
  35964. this._allEntries = new Array(initialElementCount);
  35965. this._freeEntries = new Array(initialElementCount);
  35966. for (var i = 0; i < initialElementCount; i++) {
  35967. var element = new DynamicFloatArrayElementInfo();
  35968. element.offset = i * stride;
  35969. this._allEntries[i] = element;
  35970. this._freeEntries[initialElementCount - i - 1] = element;
  35971. }
  35972. }
  35973. /**
  35974. * Allocate an element in the array.
  35975. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35976. * Beware, this offset may change when you call pack()
  35977. */
  35978. DynamicFloatArray.prototype.allocElement = function () {
  35979. if (this._freeEntries.length === 0) {
  35980. this._growBuffer();
  35981. }
  35982. var el = this._freeEntries.pop();
  35983. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35984. if (el.offset === this._firstFree) {
  35985. if (this._freeEntries.length > 0) {
  35986. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35987. }
  35988. else {
  35989. this._firstFree += this._stride;
  35990. }
  35991. }
  35992. return el;
  35993. };
  35994. /**
  35995. * Free the element corresponding to the given element info
  35996. * @param elInfo the element that describe the allocated element
  35997. */
  35998. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35999. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  36000. this._freeEntries.push(elInfo);
  36001. };
  36002. /**
  36003. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  36004. * 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().
  36005. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  36006. */
  36007. DynamicFloatArray.prototype.pack = function () {
  36008. // no free slot? no need to pack
  36009. if (this._freeEntries.length === 0) {
  36010. return this.buffer;
  36011. }
  36012. // If the buffer is already packed the last used will always be lower than the first free
  36013. // 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.
  36014. if (this._lastUsed < this._firstFree) {
  36015. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  36016. return elementsBuffer_1;
  36017. }
  36018. var s = this._stride;
  36019. // 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
  36020. var lastFree = new DynamicFloatArrayElementInfo();
  36021. lastFree.offset = this.totalElementCount * s;
  36022. this._freeEntries.push(lastFree);
  36023. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  36024. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36025. var firstFreeSlotOffset = sortedFree[0].offset;
  36026. var freeZoneSize = 1;
  36027. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  36028. var prevOffset = sortedFree[0].offset;
  36029. for (var i = 1; i < sortedFree.length; i++) {
  36030. // 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
  36031. if (firstFreeSlotOffset >= occupiedZoneSize) {
  36032. break;
  36033. }
  36034. var curFree = sortedFree[i];
  36035. var curOffset = curFree.offset;
  36036. // Compute the distance between this offset and the previous
  36037. var distance = curOffset - prevOffset;
  36038. // If the distance is the stride size, they are adjacent, it good, move to the next
  36039. if (distance === s) {
  36040. // Free zone is one element bigger
  36041. ++freeZoneSize;
  36042. // as we're about to iterate to the next, the cur becomes the previous...
  36043. prevOffset = curOffset;
  36044. continue;
  36045. }
  36046. // Distance is bigger, which means there's x element between the previous free and this one
  36047. var usedRange = (distance / s) - 1;
  36048. // Two cases the free zone is smaller than the data to move or bigger
  36049. // Copy what can fit in the free zone
  36050. var curMoveOffset = curOffset - s;
  36051. var copyCount = Math.min(freeZoneSize, usedRange);
  36052. for (var j = 0; j < copyCount; j++) {
  36053. var freeI = firstFreeSlotOffset / s;
  36054. var curI = curMoveOffset / s;
  36055. var moveEl = sortedAll[curI];
  36056. this._moveElement(moveEl, firstFreeSlotOffset);
  36057. var replacedEl = sortedAll[freeI];
  36058. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  36059. replacedEl.offset = curMoveOffset;
  36060. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  36061. sortedAll[freeI] = moveEl;
  36062. sortedAll[curI] = replacedEl;
  36063. curMoveOffset -= s;
  36064. firstFreeSlotOffset += s;
  36065. }
  36066. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  36067. if (freeZoneSize <= usedRange) {
  36068. firstFreeSlotOffset = curMoveOffset + s;
  36069. freeZoneSize = 1 + copyCount;
  36070. }
  36071. else {
  36072. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  36073. }
  36074. // as we're about to iterate to the next, the cur becomes the previous...
  36075. prevOffset = curOffset;
  36076. }
  36077. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  36078. this._lastUsed = firstFreeSlotOffset - s;
  36079. this._firstFree = firstFreeSlotOffset;
  36080. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  36081. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  36082. this._allEntries = sortedAll;
  36083. return elementsBuffer;
  36084. };
  36085. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  36086. for (var i = 0; i < this._stride; i++) {
  36087. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  36088. }
  36089. element.offset = destOffset;
  36090. };
  36091. DynamicFloatArray.prototype._growBuffer = function () {
  36092. // Allocate the new buffer with 50% more entries, copy the content of the current one
  36093. var newElCount = Math.floor(this.totalElementCount * 1.5);
  36094. var newBuffer = new Float32Array(newElCount * this._stride);
  36095. newBuffer.set(this.buffer);
  36096. var curCount = this.totalElementCount;
  36097. var addedCount = newElCount - this.totalElementCount;
  36098. for (var i = 0; i < addedCount; i++) {
  36099. var element = new DynamicFloatArrayElementInfo();
  36100. element.offset = (curCount + i) * this.stride;
  36101. this._allEntries.push(element);
  36102. this._freeEntries[addedCount - i - 1] = element;
  36103. }
  36104. this._firstFree = curCount * this.stride;
  36105. this.buffer = newBuffer;
  36106. };
  36107. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36108. /**
  36109. * Get the total count of entries that can fit in the current buffer
  36110. * @returns the elements count
  36111. */
  36112. get: function () {
  36113. return this._allEntries.length;
  36114. },
  36115. enumerable: true,
  36116. configurable: true
  36117. });
  36118. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36119. /**
  36120. * Get the count of free entries that can still be allocated without resizing the buffer
  36121. * @returns the free elements count
  36122. */
  36123. get: function () {
  36124. return this._freeEntries.length;
  36125. },
  36126. enumerable: true,
  36127. configurable: true
  36128. });
  36129. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36130. /**
  36131. * Get the count of allocated elements
  36132. * @returns the allocated elements count
  36133. */
  36134. get: function () {
  36135. return this._allEntries.length - this._freeEntries.length;
  36136. },
  36137. enumerable: true,
  36138. configurable: true
  36139. });
  36140. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36141. /**
  36142. * Return the size of one element in float
  36143. * @returns the size in float
  36144. */
  36145. get: function () {
  36146. return this._stride;
  36147. },
  36148. enumerable: true,
  36149. configurable: true
  36150. });
  36151. DynamicFloatArray.prototype.sort = function () {
  36152. var _this = this;
  36153. if (!this.compareValueOffset) {
  36154. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36155. }
  36156. var count = this.usedElementCount;
  36157. // Do we have to (re)create the sort table?
  36158. if (!this._sortTable || this._sortTable.length < count) {
  36159. // 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...
  36160. var newCount = Math.min(this.totalElementCount, count * 2);
  36161. this._sortTable = new Array(newCount);
  36162. }
  36163. if (!this._sortedTable || this._sortedTable.length !== count) {
  36164. this._sortedTable = new Array(count);
  36165. }
  36166. // Because, you know...
  36167. this.pack();
  36168. //let stride = this.stride;
  36169. //for (let i = 0; i < count; i++) {
  36170. // let si = this._sortTable[i];
  36171. // if (!si) {
  36172. // si = new SortInfo();
  36173. // this._sortTable[i] = si;
  36174. // }
  36175. // si.entry = this._allEntries[i];
  36176. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36177. // si.swapedOffset = null;
  36178. // this._sortedTable[i] = si;
  36179. //}
  36180. var curOffset = 0;
  36181. var stride = this.stride;
  36182. for (var i = 0; i < count; i++, curOffset += stride) {
  36183. var si = this._sortTable[i];
  36184. if (!si) {
  36185. si = new SortInfo();
  36186. this._sortTable[i] = si;
  36187. }
  36188. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36189. si.offset = curOffset;
  36190. si.swapedOffset = null;
  36191. this._sortedTable[i] = si;
  36192. }
  36193. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36194. if (this.sortingAscending) {
  36195. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36196. }
  36197. else {
  36198. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36199. }
  36200. var swapElements = function (src, dst) {
  36201. for (var i = 0; i < stride; i++) {
  36202. var tps = _this.buffer[dst + i];
  36203. _this.buffer[dst + i] = _this.buffer[src + i];
  36204. _this.buffer[src + i] = tps;
  36205. }
  36206. };
  36207. // 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:
  36208. // 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),
  36209. // and I still want something with a good algorithm complexity.
  36210. // 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,
  36211. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36212. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36213. // 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
  36214. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36215. // 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
  36216. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36217. for (var i = 0; i < count; i++) {
  36218. // Get the element to move
  36219. var sourceSI = this._sortedTable[i];
  36220. var destSI = this._sortTable[i];
  36221. var sourceOff = sourceSI.offset;
  36222. // If the source changed location, find the new one
  36223. if (sourceSI.swapedOffset) {
  36224. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36225. var curSI = sourceSI;
  36226. while (curSI.swapedOffset) {
  36227. curSI = this._sortTable[curSI.swapedOffset / stride];
  36228. }
  36229. // Finally get the right location
  36230. sourceOff = curSI.offset;
  36231. }
  36232. // Tag the element being replaced with its new location
  36233. destSI.swapedOffset = sourceOff;
  36234. // Swap elements (only if needed)
  36235. if (sourceOff !== destSI.offset) {
  36236. swapElements(sourceOff, destSI.offset);
  36237. }
  36238. // Update the offset in the corresponding DFAE
  36239. //sourceSI.entry.offset = destSI.entry.offset;
  36240. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36241. }
  36242. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36243. return true;
  36244. };
  36245. return DynamicFloatArray;
  36246. })();
  36247. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36248. var SortInfo = (function () {
  36249. function SortInfo() {
  36250. this.compareData = this.offset = this.swapedOffset = null;
  36251. }
  36252. return SortInfo;
  36253. })();
  36254. })(BABYLON || (BABYLON = {}));
  36255. var BABYLON;
  36256. (function (BABYLON) {
  36257. /**
  36258. * This class given information about a given character.
  36259. */
  36260. var CharInfo = (function () {
  36261. function CharInfo() {
  36262. }
  36263. return CharInfo;
  36264. })();
  36265. BABYLON.CharInfo = CharInfo;
  36266. var FontTexture = (function (_super) {
  36267. __extends(FontTexture, _super);
  36268. /**
  36269. * Create a new instance of the FontTexture class
  36270. * @param name the name of the texture
  36271. * @param font the font to use, use the W3C CSS notation
  36272. * @param scene the scene that owns the texture
  36273. * @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
  36274. * @param samplingMode the texture sampling mode
  36275. * @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.
  36276. */
  36277. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  36278. if (maxCharCount === void 0) { maxCharCount = 200; }
  36279. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36280. if (superSample === void 0) { superSample = false; }
  36281. _super.call(this, null, scene, true, false, samplingMode);
  36282. this._charInfos = {};
  36283. this._curCharCount = 0;
  36284. this._lastUpdateCharCount = -1;
  36285. this._usedCounter = 1;
  36286. this.name = name;
  36287. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36288. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36289. this._superSample = false;
  36290. if (superSample) {
  36291. var sfont = this.getSuperSampleFont(font);
  36292. if (sfont) {
  36293. this._superSample = true;
  36294. font = sfont;
  36295. }
  36296. }
  36297. // First canvas creation to determine the size of the texture to create
  36298. this._canvas = document.createElement("canvas");
  36299. this._context = this._canvas.getContext("2d");
  36300. this._context.font = font;
  36301. this._context.fillStyle = "white";
  36302. var res = this.getFontHeight(font);
  36303. this._lineHeightSuper = res.height;
  36304. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  36305. this._offset = res.offset - 1;
  36306. var maxCharWidth = this._context.measureText("W").width;
  36307. this._spaceWidthSuper = this._context.measureText(" ").width;
  36308. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  36309. // This is an approximate size, but should always be able to fit at least the maxCharCount
  36310. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  36311. var edge = Math.sqrt(totalEstSurface);
  36312. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  36313. // Create the texture that will store the font characters
  36314. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  36315. var textureSize = this.getSize();
  36316. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  36317. this._canvas = document.createElement("canvas");
  36318. this._canvas.width = textureSize.width;
  36319. this._canvas.height = textureSize.height;
  36320. this._context = this._canvas.getContext("2d");
  36321. this._context.textBaseline = "top";
  36322. this._context.font = font;
  36323. this._context.fillStyle = "white";
  36324. this._context.imageSmoothingEnabled = false;
  36325. this._currentFreePosition = BABYLON.Vector2.Zero();
  36326. // Add the basic ASCII based characters
  36327. for (var i = 0x20; i < 0x7F; i++) {
  36328. var c = String.fromCharCode(i);
  36329. this.getChar(c);
  36330. }
  36331. this.update();
  36332. }
  36333. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  36334. get: function () {
  36335. return this._superSample;
  36336. },
  36337. enumerable: true,
  36338. configurable: true
  36339. });
  36340. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  36341. get: function () {
  36342. return this._spaceWidth;
  36343. },
  36344. enumerable: true,
  36345. configurable: true
  36346. });
  36347. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  36348. get: function () {
  36349. return this._lineHeight;
  36350. },
  36351. enumerable: true,
  36352. configurable: true
  36353. });
  36354. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  36355. if (supersample === void 0) { supersample = false; }
  36356. var s = scene;
  36357. if (!s.__fontTextureCache__) {
  36358. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  36359. }
  36360. var dic = s.__fontTextureCache__;
  36361. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36362. var ft = dic.get(lfn);
  36363. if (ft) {
  36364. ++ft._usedCounter;
  36365. return ft;
  36366. }
  36367. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  36368. dic.add(lfn, ft);
  36369. return ft;
  36370. };
  36371. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  36372. if (supersample === void 0) { supersample = false; }
  36373. var s = scene;
  36374. var dic = s.__fontTextureCache__;
  36375. if (!dic) {
  36376. return;
  36377. }
  36378. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  36379. var font = dic.get(lfn);
  36380. if (--font._usedCounter === 0) {
  36381. dic.remove(lfn);
  36382. font.dispose();
  36383. }
  36384. };
  36385. /**
  36386. * Make sure the given char is present in the font map.
  36387. * @param char the character to get or add
  36388. * @return the CharInfo instance corresponding to the given character
  36389. */
  36390. FontTexture.prototype.getChar = function (char) {
  36391. if (char.length !== 1) {
  36392. return null;
  36393. }
  36394. var info = this._charInfos[char];
  36395. if (info) {
  36396. return info;
  36397. }
  36398. info = new CharInfo();
  36399. var measure = this._context.measureText(char);
  36400. var textureSize = this.getSize();
  36401. // we reached the end of the current line?
  36402. var width = Math.round(measure.width);
  36403. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  36404. var yMargin = xMargin;
  36405. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  36406. this._currentFreePosition.x = 0;
  36407. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  36408. // No more room?
  36409. if (this._currentFreePosition.y > textureSize.height) {
  36410. return this.getChar("!");
  36411. }
  36412. }
  36413. // Draw the character in the texture
  36414. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  36415. // Fill the CharInfo object
  36416. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  36417. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  36418. info.charWidth = this._superSample ? (width / 2) : width;
  36419. // Add the info structure
  36420. this._charInfos[char] = info;
  36421. this._curCharCount++;
  36422. // Set the next position
  36423. this._currentFreePosition.x += width + xMargin;
  36424. return info;
  36425. };
  36426. FontTexture.prototype.measureText = function (text, tabulationSize) {
  36427. if (tabulationSize === void 0) { tabulationSize = 4; }
  36428. var maxWidth = 0;
  36429. var curWidth = 0;
  36430. var lineCount = 1;
  36431. var charxpos = 0;
  36432. // Parse each char of the string
  36433. for (var _i = 0; _i < text.length; _i++) {
  36434. var char = text[_i];
  36435. // Next line feed?
  36436. if (char === "\n") {
  36437. maxWidth = Math.max(maxWidth, curWidth);
  36438. charxpos = 0;
  36439. curWidth = 0;
  36440. ++lineCount;
  36441. continue;
  36442. }
  36443. // Tabulation ?
  36444. if (char === "\t") {
  36445. var nextPos = charxpos + tabulationSize;
  36446. nextPos = nextPos - (nextPos % tabulationSize);
  36447. curWidth += (nextPos - charxpos) * this.spaceWidth;
  36448. charxpos = nextPos;
  36449. continue;
  36450. }
  36451. if (char < " ") {
  36452. continue;
  36453. }
  36454. curWidth += this.getChar(char).charWidth;
  36455. ++charxpos;
  36456. }
  36457. maxWidth = Math.max(maxWidth, curWidth);
  36458. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  36459. };
  36460. FontTexture.prototype.getSuperSampleFont = function (font) {
  36461. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  36462. 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*$/;
  36463. var res = font.toLocaleLowerCase().match(regex);
  36464. if (res == null) {
  36465. return null;
  36466. }
  36467. var size = parseInt(res[4]);
  36468. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  36469. var newFont = "";
  36470. for (var j = 1; j < res.length; j++) {
  36471. if (res[j] != null) {
  36472. newFont += res[j] + " ";
  36473. }
  36474. }
  36475. return newFont;
  36476. };
  36477. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  36478. FontTexture.prototype.getFontHeight = function (font) {
  36479. var fontDraw = document.createElement("canvas");
  36480. var ctx = fontDraw.getContext('2d');
  36481. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  36482. ctx.textBaseline = 'top';
  36483. ctx.fillStyle = 'white';
  36484. ctx.font = font;
  36485. ctx.fillText('jH|', 0, 0);
  36486. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  36487. var start = -1;
  36488. var end = -1;
  36489. for (var row = 0; row < fontDraw.height; row++) {
  36490. for (var column = 0; column < fontDraw.width; column++) {
  36491. var index = (row * fontDraw.width + column) * 4;
  36492. if (pixels[index] === 0) {
  36493. if (column === fontDraw.width - 1 && start !== -1) {
  36494. end = row;
  36495. row = fontDraw.height;
  36496. break;
  36497. }
  36498. continue;
  36499. }
  36500. else {
  36501. if (start === -1) {
  36502. start = row;
  36503. }
  36504. break;
  36505. }
  36506. }
  36507. }
  36508. return { height: (end - start) + 1, offset: start - 1 };
  36509. };
  36510. Object.defineProperty(FontTexture.prototype, "canRescale", {
  36511. get: function () {
  36512. return false;
  36513. },
  36514. enumerable: true,
  36515. configurable: true
  36516. });
  36517. FontTexture.prototype.getContext = function () {
  36518. return this._context;
  36519. };
  36520. /**
  36521. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  36522. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  36523. */
  36524. FontTexture.prototype.update = function () {
  36525. // Update only if there's new char added since the previous update
  36526. if (this._lastUpdateCharCount < this._curCharCount) {
  36527. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  36528. this._lastUpdateCharCount = this._curCharCount;
  36529. }
  36530. };
  36531. // cloning should be prohibited, there's no point to duplicate this texture at all
  36532. FontTexture.prototype.clone = function () {
  36533. return null;
  36534. };
  36535. return FontTexture;
  36536. })(BABYLON.Texture);
  36537. BABYLON.FontTexture = FontTexture;
  36538. })(BABYLON || (BABYLON = {}));
  36539. var BABYLON;
  36540. (function (BABYLON) {
  36541. var MapTexture = (function (_super) {
  36542. __extends(MapTexture, _super);
  36543. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  36544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36545. if (useMipMap === void 0) { useMipMap = false; }
  36546. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  36547. this.name = name;
  36548. this._size = size;
  36549. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36550. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36551. // Create the rectPackMap that will allocate portion of the texture
  36552. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  36553. // Create the texture that will store the content
  36554. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  36555. }
  36556. /**
  36557. * Allocate a rectangle of a given size in the texture map
  36558. * @param size the size of the rectangle to allocation
  36559. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  36560. */
  36561. MapTexture.prototype.allocateRect = function (size) {
  36562. return this._rectPackingMap.addRect(size);
  36563. };
  36564. /**
  36565. * Free a given rectangle from the texture map
  36566. * @param rectInfo the instance corresponding to the rect to free.
  36567. */
  36568. MapTexture.prototype.freeRect = function (rectInfo) {
  36569. if (rectInfo) {
  36570. rectInfo.freeContent();
  36571. }
  36572. };
  36573. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  36574. /**
  36575. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  36576. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  36577. * @returns {}
  36578. */
  36579. get: function () {
  36580. return this._rectPackingMap.freeSpace;
  36581. },
  36582. enumerable: true,
  36583. configurable: true
  36584. });
  36585. /**
  36586. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  36587. * 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.
  36588. * Don't forget to call unbindTexture when you're done rendering
  36589. * @param rect the zone to render to
  36590. * @param clear true to clear the portion's color/depth data
  36591. */
  36592. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  36593. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  36594. };
  36595. /**
  36596. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  36597. * 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.
  36598. * Don't forget to call unbindTexture when you're done rendering
  36599. * @param pos the position into the texture
  36600. * @param size the portion to fit the clip space to
  36601. * @param clear true to clear the portion's color/depth data
  36602. */
  36603. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  36604. var engine = this.getScene().getEngine();
  36605. engine.bindFramebuffer(this._texture);
  36606. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  36607. if (clear) {
  36608. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  36609. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  36610. }
  36611. };
  36612. /**
  36613. * Unbind the texture map from the rendering engine.
  36614. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  36615. * @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.
  36616. */
  36617. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  36618. // Dump ?
  36619. if (dumpForDebug) {
  36620. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  36621. }
  36622. var engine = this.getScene().getEngine();
  36623. if (this._replacedViewport) {
  36624. engine.setViewport(this._replacedViewport);
  36625. this._replacedViewport = null;
  36626. }
  36627. engine.unBindFramebuffer(this._texture);
  36628. };
  36629. Object.defineProperty(MapTexture.prototype, "canRescale", {
  36630. get: function () {
  36631. return false;
  36632. },
  36633. enumerable: true,
  36634. configurable: true
  36635. });
  36636. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  36637. // Anyway, there's not much point to use this method for this kind of texture I guess
  36638. MapTexture.prototype.clone = function () {
  36639. return null;
  36640. };
  36641. return MapTexture;
  36642. })(BABYLON.Texture);
  36643. BABYLON.MapTexture = MapTexture;
  36644. })(BABYLON || (BABYLON = {}));
  36645. var BABYLON;
  36646. (function (BABYLON) {
  36647. /**
  36648. * Stores 2D Bounding Information.
  36649. * This class handles a circle area and a bounding rectangle one.
  36650. */
  36651. var BoundingInfo2D = (function () {
  36652. function BoundingInfo2D() {
  36653. this.radius = 0;
  36654. this.center = BABYLON.Vector2.Zero();
  36655. this.extent = BABYLON.Vector2.Zero();
  36656. }
  36657. /**
  36658. * Create a BoundingInfo2D object from a given size
  36659. * @param size the size that will be used to set the extend, radius will be computed from it.
  36660. */
  36661. BoundingInfo2D.CreateFromSize = function (size) {
  36662. var r = new BoundingInfo2D();
  36663. BoundingInfo2D.CreateFromSizeToRef(size, r);
  36664. return r;
  36665. };
  36666. /**
  36667. * Create a BoundingInfo2D object from a given radius
  36668. * @param radius the radius to use, the extent will be computed from it.
  36669. */
  36670. BoundingInfo2D.CreateFromRadius = function (radius) {
  36671. var r = new BoundingInfo2D();
  36672. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  36673. return r;
  36674. };
  36675. /**
  36676. * Create a BoundingInfo2D object from a list of points.
  36677. * The resulted object will be the smallest bounding area that includes all the given points.
  36678. * @param points an array of points to compute the bounding object from.
  36679. */
  36680. BoundingInfo2D.CreateFromPoints = function (points) {
  36681. var r = new BoundingInfo2D();
  36682. BoundingInfo2D.CreateFromPointsToRef(points, r);
  36683. return r;
  36684. };
  36685. /**
  36686. * Update a BoundingInfo2D object using the given Size as input
  36687. * @param size the bounding data will be computed from this size.
  36688. * @param b must be a valid/allocated object, it will contain the result of the operation
  36689. */
  36690. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  36691. if (!size) {
  36692. size = BABYLON.Size.Zero();
  36693. }
  36694. b.center.x = +size.width / 2;
  36695. b.center.y = +size.height / 2;
  36696. b.extent.x = b.center.x;
  36697. b.extent.y = b.center.y;
  36698. b.radius = b.extent.length();
  36699. };
  36700. /**
  36701. * Update a BoundingInfo2D object using the given radius as input
  36702. * @param radius the bounding data will be computed from this radius
  36703. * @param b must be a valid/allocated object, it will contain the result of the operation
  36704. */
  36705. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  36706. b.center.x = b.center.y = 0;
  36707. var r = +radius;
  36708. b.extent.x = r;
  36709. b.extent.y = r;
  36710. b.radius = r;
  36711. };
  36712. /**
  36713. * Update a BoundingInfo2D object using the given points array as input
  36714. * @param points the point array to use to update the bounding data
  36715. * @param b must be a valid/allocated object, it will contain the result of the operation
  36716. */
  36717. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  36718. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  36719. for (var _i = 0; _i < points.length; _i++) {
  36720. var p = points[_i];
  36721. xmin = Math.min(p.x, xmin);
  36722. xmax = Math.max(p.x, xmax);
  36723. ymin = Math.min(p.y, ymin);
  36724. ymax = Math.max(p.y, ymax);
  36725. }
  36726. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  36727. };
  36728. /**
  36729. * Update a BoundingInfo2D object using the given min/max values as input
  36730. * @param xmin the smallest x coordinate
  36731. * @param xmax the biggest x coordinate
  36732. * @param ymin the smallest y coordinate
  36733. * @param ymax the buggest y coordinate
  36734. * @param b must be a valid/allocated object, it will contain the result of the operation
  36735. */
  36736. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  36737. var w = xmax - xmin;
  36738. var h = ymax - ymin;
  36739. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  36740. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  36741. b.radius = b.extent.length();
  36742. };
  36743. /**
  36744. * Duplicate this instance and return a new one
  36745. * @return the duplicated instance
  36746. */
  36747. BoundingInfo2D.prototype.clone = function () {
  36748. var r = new BoundingInfo2D();
  36749. r.center = this.center.clone();
  36750. r.radius = this.radius;
  36751. r.extent = this.extent.clone();
  36752. return r;
  36753. };
  36754. BoundingInfo2D.prototype.clear = function () {
  36755. this.center.copyFromFloats(0, 0);
  36756. this.radius = 0;
  36757. this.extent.copyFromFloats(0, 0);
  36758. };
  36759. BoundingInfo2D.prototype.copyFrom = function (src) {
  36760. this.center.copyFrom(src.center);
  36761. this.radius = src.radius;
  36762. this.extent.copyFrom(src.extent);
  36763. };
  36764. /**
  36765. * return the max extend of the bounding info
  36766. */
  36767. BoundingInfo2D.prototype.max = function () {
  36768. var r = BABYLON.Vector2.Zero();
  36769. this.maxToRef(r);
  36770. return r;
  36771. };
  36772. /**
  36773. * Update a vector2 with the max extend of the bounding info
  36774. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  36775. */
  36776. BoundingInfo2D.prototype.maxToRef = function (result) {
  36777. result.x = this.center.x + this.extent.x;
  36778. result.y = this.center.y + this.extent.y;
  36779. };
  36780. /**
  36781. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  36782. * @param matrix the transformation matrix to apply
  36783. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  36784. */
  36785. BoundingInfo2D.prototype.transform = function (matrix) {
  36786. var r = new BoundingInfo2D();
  36787. this.transformToRef(matrix, r);
  36788. return r;
  36789. };
  36790. /**
  36791. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  36792. * @param other the second BoundingInfo2D to compute the union with this one
  36793. * @return a new instance containing the result of the union
  36794. */
  36795. BoundingInfo2D.prototype.union = function (other) {
  36796. var r = new BoundingInfo2D();
  36797. this.unionToRef(other, r);
  36798. return r;
  36799. };
  36800. /**
  36801. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  36802. * 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.
  36803. * @param matrix The matrix to use to compute the transformation
  36804. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  36805. */
  36806. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  36807. // Construct a bounding box based on the extent values
  36808. var p = BoundingInfo2D._transform;
  36809. p[0].x = this.center.x + this.extent.x;
  36810. p[0].y = this.center.y + this.extent.y;
  36811. p[1].x = this.center.x + this.extent.x;
  36812. p[1].y = this.center.y - this.extent.y;
  36813. p[2].x = this.center.x - this.extent.x;
  36814. p[2].y = this.center.y - this.extent.y;
  36815. p[3].x = this.center.x - this.extent.x;
  36816. p[3].y = this.center.y + this.extent.y;
  36817. // Transform the four points of the bounding box with the matrix
  36818. for (var i = 0; i < 4; i++) {
  36819. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  36820. }
  36821. BoundingInfo2D.CreateFromPointsToRef(p, result);
  36822. };
  36823. /**
  36824. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  36825. * 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.
  36826. * @param other the second object used to compute the union
  36827. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  36828. */
  36829. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  36830. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  36831. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  36832. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  36833. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  36834. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  36835. };
  36836. /**
  36837. * Check if the given point is inside the BoundingInfo.
  36838. * The test is first made on the radius, then inside the rectangle described by the extent
  36839. * @param pickPosition the position to test
  36840. * @return true if the point is inside, false otherwise
  36841. */
  36842. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  36843. // is it inside the radius?
  36844. var pickLocal = pickPosition.subtract(this.center);
  36845. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  36846. // is it inside the rectangle?
  36847. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  36848. }
  36849. return false;
  36850. };
  36851. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  36852. return BoundingInfo2D;
  36853. })();
  36854. BABYLON.BoundingInfo2D = BoundingInfo2D;
  36855. })(BABYLON || (BABYLON = {}));
  36856. var BABYLON;
  36857. (function (BABYLON) {
  36858. /**
  36859. * Base class implementing the ILocable interface.
  36860. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  36861. */
  36862. var LockableBase = (function () {
  36863. function LockableBase() {
  36864. }
  36865. LockableBase.prototype.isLocked = function () {
  36866. return this._isLocked;
  36867. };
  36868. LockableBase.prototype.lock = function () {
  36869. if (this._isLocked) {
  36870. return true;
  36871. }
  36872. this.onLock();
  36873. this._isLocked = true;
  36874. return false;
  36875. };
  36876. /**
  36877. * Protected handler that will be called when the instance is about to be locked.
  36878. */
  36879. LockableBase.prototype.onLock = function () {
  36880. };
  36881. return LockableBase;
  36882. })();
  36883. BABYLON.LockableBase = LockableBase;
  36884. var SolidColorBrush2D = (function (_super) {
  36885. __extends(SolidColorBrush2D, _super);
  36886. function SolidColorBrush2D(color, lock) {
  36887. if (lock === void 0) { lock = false; }
  36888. _super.call(this);
  36889. this._color = color;
  36890. if (lock) {
  36891. {
  36892. this.lock();
  36893. }
  36894. }
  36895. }
  36896. /**
  36897. * Return true if the brush is transparent, false if it's totally opaque
  36898. */
  36899. SolidColorBrush2D.prototype.isTransparent = function () {
  36900. return this._color && this._color.a < 1.0;
  36901. };
  36902. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  36903. /**
  36904. * The color used by this instance to render
  36905. * @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.
  36906. */
  36907. get: function () {
  36908. return this._color;
  36909. },
  36910. set: function (value) {
  36911. if (this.isLocked()) {
  36912. return;
  36913. }
  36914. this._color = value;
  36915. },
  36916. enumerable: true,
  36917. configurable: true
  36918. });
  36919. /**
  36920. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  36921. */
  36922. SolidColorBrush2D.prototype.toString = function () {
  36923. return this._color.toHexString();
  36924. };
  36925. SolidColorBrush2D = __decorate([
  36926. BABYLON.className("SolidColorBrush2D")
  36927. ], SolidColorBrush2D);
  36928. return SolidColorBrush2D;
  36929. })(LockableBase);
  36930. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  36931. var GradientColorBrush2D = (function (_super) {
  36932. __extends(GradientColorBrush2D, _super);
  36933. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  36934. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  36935. if (rotation === void 0) { rotation = 0; }
  36936. if (scale === void 0) { scale = 1; }
  36937. if (lock === void 0) { lock = false; }
  36938. _super.call(this);
  36939. this._color1 = color1;
  36940. this._color2 = color2;
  36941. this._translation = translation;
  36942. this._rotation = rotation;
  36943. this._scale = scale;
  36944. if (lock) {
  36945. this.lock();
  36946. }
  36947. }
  36948. /**
  36949. * Return true if the brush is transparent, false if it's totally opaque
  36950. */
  36951. GradientColorBrush2D.prototype.isTransparent = function () {
  36952. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  36953. };
  36954. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  36955. /**
  36956. * First color, the blend will start from this color
  36957. */
  36958. get: function () {
  36959. return this._color1;
  36960. },
  36961. set: function (value) {
  36962. if (this.isLocked()) {
  36963. return;
  36964. }
  36965. this._color1 = value;
  36966. },
  36967. enumerable: true,
  36968. configurable: true
  36969. });
  36970. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  36971. /**
  36972. * Second color, the blend will end to this color
  36973. */
  36974. get: function () {
  36975. return this._color2;
  36976. },
  36977. set: function (value) {
  36978. if (this.isLocked()) {
  36979. return;
  36980. }
  36981. this._color2 = value;
  36982. },
  36983. enumerable: true,
  36984. configurable: true
  36985. });
  36986. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  36987. /**
  36988. * Translation vector to apply on the blend
  36989. * Default is [0;0]
  36990. */
  36991. get: function () {
  36992. return this._translation;
  36993. },
  36994. set: function (value) {
  36995. if (this.isLocked()) {
  36996. return;
  36997. }
  36998. this._translation = value;
  36999. },
  37000. enumerable: true,
  37001. configurable: true
  37002. });
  37003. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  37004. /**
  37005. * Rotation in radian to apply to the brush
  37006. * Default direction of the brush is vertical, you can change this using this property.
  37007. * Default is 0.
  37008. */
  37009. get: function () {
  37010. return this._rotation;
  37011. },
  37012. set: function (value) {
  37013. if (this.isLocked()) {
  37014. return;
  37015. }
  37016. this._rotation = value;
  37017. },
  37018. enumerable: true,
  37019. configurable: true
  37020. });
  37021. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  37022. /**
  37023. * Scale factor to apply to the gradient.
  37024. * Default is 1: no scale.
  37025. */
  37026. get: function () {
  37027. return this._scale;
  37028. },
  37029. set: function (value) {
  37030. if (this.isLocked()) {
  37031. return;
  37032. }
  37033. this._scale = value;
  37034. },
  37035. enumerable: true,
  37036. configurable: true
  37037. });
  37038. /**
  37039. * Return a string describing the brush
  37040. */
  37041. GradientColorBrush2D.prototype.toString = function () {
  37042. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  37043. };
  37044. /**
  37045. * Build a unique key string for the given parameters
  37046. */
  37047. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  37048. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  37049. };
  37050. GradientColorBrush2D = __decorate([
  37051. BABYLON.className("GradientColorBrush2D")
  37052. ], GradientColorBrush2D);
  37053. return GradientColorBrush2D;
  37054. })(LockableBase);
  37055. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  37056. })(BABYLON || (BABYLON = {}));
  37057. var BABYLON;
  37058. (function (BABYLON) {
  37059. var Prim2DClassInfo = (function () {
  37060. function Prim2DClassInfo() {
  37061. }
  37062. return Prim2DClassInfo;
  37063. })();
  37064. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  37065. var Prim2DPropInfo = (function () {
  37066. function Prim2DPropInfo() {
  37067. }
  37068. Prim2DPropInfo.PROPKIND_MODEL = 1;
  37069. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  37070. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  37071. return Prim2DPropInfo;
  37072. })();
  37073. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  37074. /**
  37075. * Custom type of the propertyChanged observable
  37076. */
  37077. var PropertyChangedInfo = (function () {
  37078. function PropertyChangedInfo() {
  37079. }
  37080. return PropertyChangedInfo;
  37081. })();
  37082. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  37083. var ClassTreeInfo = (function () {
  37084. function ClassTreeInfo(baseClass, type, classContentFactory) {
  37085. this._baseClass = baseClass;
  37086. this._type = type;
  37087. this._subClasses = new Array();
  37088. this._levelContent = new BABYLON.StringDictionary();
  37089. this._classContentFactory = classContentFactory;
  37090. }
  37091. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  37092. get: function () {
  37093. if (!this._classContent) {
  37094. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  37095. }
  37096. return this._classContent;
  37097. },
  37098. enumerable: true,
  37099. configurable: true
  37100. });
  37101. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  37102. get: function () {
  37103. return this._type;
  37104. },
  37105. enumerable: true,
  37106. configurable: true
  37107. });
  37108. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  37109. get: function () {
  37110. return this._levelContent;
  37111. },
  37112. enumerable: true,
  37113. configurable: true
  37114. });
  37115. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  37116. get: function () {
  37117. if (!this._fullContent) {
  37118. var dic = new BABYLON.StringDictionary();
  37119. var curLevel = this;
  37120. while (curLevel) {
  37121. curLevel.levelContent.forEach(function (k, v) { return dic.add(k, v); });
  37122. curLevel = curLevel._baseClass;
  37123. }
  37124. this._fullContent = dic;
  37125. }
  37126. return this._fullContent;
  37127. },
  37128. enumerable: true,
  37129. configurable: true
  37130. });
  37131. ClassTreeInfo.prototype.getLevelOf = function (type) {
  37132. // Are we already there?
  37133. if (type === this._type) {
  37134. return this;
  37135. }
  37136. var baseProto = Object.getPrototypeOf(type);
  37137. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  37138. if (!curProtoContent) {
  37139. this.getLevelOf(baseProto);
  37140. }
  37141. return this.getOrAddType(baseProto, type);
  37142. };
  37143. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  37144. // Are we at the level corresponding to the baseType?
  37145. // If so, get or add the level we're looking for
  37146. if (baseType === this._type) {
  37147. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  37148. var subType = _a[_i];
  37149. if (subType.type === type) {
  37150. return subType.node;
  37151. }
  37152. }
  37153. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  37154. var info = { type: type, node: node };
  37155. this._subClasses.push(info);
  37156. return info.node;
  37157. }
  37158. // Recurse down to keep looking for the node corresponding to the baseTypeName
  37159. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  37160. var subType = _c[_b];
  37161. var info = subType.node.getOrAddType(baseType, type);
  37162. if (info) {
  37163. return info;
  37164. }
  37165. }
  37166. return null;
  37167. };
  37168. ClassTreeInfo.get = function (type) {
  37169. var dic = type["__classTreeInfo"];
  37170. if (!dic) {
  37171. return null;
  37172. }
  37173. return dic.getLevelOf(type);
  37174. };
  37175. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  37176. var dic = type["__classTreeInfo"];
  37177. if (!dic) {
  37178. dic = new ClassTreeInfo(null, type, classContentFactory);
  37179. type["__classTreeInfo"] = dic;
  37180. }
  37181. return dic;
  37182. };
  37183. return ClassTreeInfo;
  37184. })();
  37185. BABYLON.ClassTreeInfo = ClassTreeInfo;
  37186. var SmartPropertyPrim = (function () {
  37187. function SmartPropertyPrim() {
  37188. this._flags = 0;
  37189. this._modelKey = null;
  37190. this._instanceDirtyFlags = 0;
  37191. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  37192. this.animations = new Array();
  37193. }
  37194. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  37195. /**
  37196. * Check if the object is disposed or not.
  37197. * @returns true if the object is dispose, false otherwise.
  37198. */
  37199. get: function () {
  37200. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  37201. },
  37202. enumerable: true,
  37203. configurable: true
  37204. });
  37205. /**
  37206. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  37207. * @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.
  37208. */
  37209. SmartPropertyPrim.prototype.dispose = function () {
  37210. if (this.isDisposed) {
  37211. return false;
  37212. }
  37213. // Don't set to null, it may upset somebody...
  37214. this.animations.splice(0);
  37215. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  37216. return true;
  37217. };
  37218. /**
  37219. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  37220. * Look at Sprite2D for more information
  37221. */
  37222. SmartPropertyPrim.prototype.getAnimatables = function () {
  37223. return new Array();
  37224. };
  37225. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  37226. /**
  37227. * Property giving the Model Key associated to the property.
  37228. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  37229. * @returns the model key string.
  37230. */
  37231. get: function () {
  37232. var _this = this;
  37233. // No need to compute it?
  37234. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  37235. return this._modelKey;
  37236. }
  37237. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  37238. var propDic = this.propDic;
  37239. propDic.forEach(function (k, v) {
  37240. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  37241. var propVal = _this[v.name];
  37242. // 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
  37243. if (propVal && propVal.constructor === Array) {
  37244. var firstVal = propVal[0];
  37245. if (!firstVal) {
  37246. propVal = 0;
  37247. }
  37248. else {
  37249. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  37250. }
  37251. }
  37252. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  37253. }
  37254. });
  37255. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  37256. this._modelKey = modelKey;
  37257. return modelKey;
  37258. },
  37259. enumerable: true,
  37260. configurable: true
  37261. });
  37262. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  37263. /**
  37264. * States if the Primitive is dirty and should be rendered again next time.
  37265. * @returns true is dirty, false otherwise
  37266. */
  37267. get: function () {
  37268. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  37269. },
  37270. enumerable: true,
  37271. configurable: true
  37272. });
  37273. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  37274. /**
  37275. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  37276. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  37277. */
  37278. get: function () {
  37279. if (!this._propInfo) {
  37280. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  37281. if (!cti) {
  37282. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  37283. }
  37284. this._propInfo = cti.fullContent;
  37285. }
  37286. return this._propInfo;
  37287. },
  37288. enumerable: true,
  37289. configurable: true
  37290. });
  37291. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  37292. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  37293. var node = dic.getLevelOf(target);
  37294. var propInfo = node.levelContent.get(propId.toString());
  37295. if (propInfo) {
  37296. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  37297. }
  37298. // Create, setup and add the PropInfo object to our prop dictionary
  37299. propInfo = new Prim2DPropInfo();
  37300. propInfo.id = propId;
  37301. propInfo.flagId = Math.pow(2, propId);
  37302. propInfo.kind = kind;
  37303. propInfo.name = propName;
  37304. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  37305. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  37306. propInfo.typeLevelCompare = typeLevelCompare;
  37307. node.levelContent.add(propName, propInfo);
  37308. return propInfo;
  37309. };
  37310. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  37311. // Nothing to nothing: nothing to do!
  37312. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  37313. return true;
  37314. }
  37315. // Check value unchanged
  37316. if ((curValue != null) && (newValue != null)) {
  37317. if (typeof (curValue.equals) == "function") {
  37318. if (curValue.equals(newValue)) {
  37319. return true;
  37320. }
  37321. }
  37322. else {
  37323. if (curValue === newValue) {
  37324. return true;
  37325. }
  37326. }
  37327. }
  37328. return false;
  37329. };
  37330. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  37331. if (this.isDisposed) {
  37332. return;
  37333. }
  37334. var i = propertyName.indexOf(".");
  37335. if (i !== -1) {
  37336. propertyName = propertyName.substr(0, i);
  37337. }
  37338. var propInfo = this.propDic.get(propertyName);
  37339. if (!propInfo) {
  37340. return;
  37341. }
  37342. var newValue = this[propertyName];
  37343. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  37344. };
  37345. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  37346. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37347. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  37348. if (this instanceof BABYLON.Prim2DBase) {
  37349. var curprim = this;
  37350. while (curprim) {
  37351. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  37352. if (curprim.isSizeAuto) {
  37353. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  37354. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  37355. }
  37356. if (curprim instanceof BABYLON.Group2D) {
  37357. if (curprim.isRenderableGroup) {
  37358. break;
  37359. }
  37360. }
  37361. curprim = curprim.parent;
  37362. }
  37363. }
  37364. };
  37365. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  37366. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  37367. if (propInfo.dirtyBoundingInfo) {
  37368. this._boundingBoxDirty();
  37369. }
  37370. else if (propInfo.dirtyParentBoundingInfo) {
  37371. var p = this._parent;
  37372. if (p != null) {
  37373. p._boundingBoxDirty();
  37374. }
  37375. }
  37376. // Trigger property changed
  37377. var info = SmartPropertyPrim.propChangedInfo;
  37378. info.oldValue = curValue;
  37379. info.newValue = newValue;
  37380. info.propertyName = propName;
  37381. var propMask = propInfo.flagId;
  37382. this.propertyChanged.notifyObservers(info, propMask);
  37383. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  37384. if (this instanceof BABYLON.Group2D) {
  37385. this.handleGroupChanged(propInfo);
  37386. }
  37387. // Check for parent layout dirty
  37388. if (this instanceof BABYLON.Prim2DBase) {
  37389. var p = this._parent;
  37390. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  37391. p._setLayoutDirty();
  37392. }
  37393. }
  37394. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  37395. var instanceDirty = false;
  37396. if (typeLevelCompare && curValue != null && newValue != null) {
  37397. var cvProto = curValue.__proto__;
  37398. var nvProto = newValue.__proto__;
  37399. instanceDirty = (cvProto === nvProto);
  37400. }
  37401. // Set the dirty flags
  37402. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  37403. this.onPrimitivePropertyDirty(SmartPropertyPrim.flagModelDirty);
  37404. }
  37405. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  37406. this.onPrimitivePropertyDirty(propMask);
  37407. }
  37408. };
  37409. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  37410. if (!this.isDirty) {
  37411. this.onPrimBecomesDirty();
  37412. }
  37413. this._instanceDirtyFlags |= propFlagId;
  37414. };
  37415. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  37416. };
  37417. /**
  37418. * Check if a given set of properties are dirty or not.
  37419. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37420. * @return true if at least one property is dirty, false if none of them are.
  37421. */
  37422. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  37423. return (this._instanceDirtyFlags & flags) !== 0;
  37424. };
  37425. /**
  37426. * Clear a given set of properties.
  37427. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  37428. * @return the new set of property still marked as dirty
  37429. */
  37430. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  37431. this._instanceDirtyFlags &= ~flags;
  37432. return this._instanceDirtyFlags;
  37433. };
  37434. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  37435. this._instanceDirtyFlags = 0;
  37436. };
  37437. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  37438. /**
  37439. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  37440. */
  37441. get: function () {
  37442. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  37443. this.updateLevelBoundingInfo();
  37444. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  37445. }
  37446. return this._levelBoundingInfo;
  37447. },
  37448. enumerable: true,
  37449. configurable: true
  37450. });
  37451. /**
  37452. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  37453. */
  37454. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  37455. };
  37456. /**
  37457. * Property method called when the Primitive becomes dirty
  37458. */
  37459. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  37460. };
  37461. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  37462. return function (target, propName, descriptor) {
  37463. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  37464. if (piStore) {
  37465. piStore(propInfo);
  37466. }
  37467. var getter = descriptor.get, setter = descriptor.set;
  37468. // Overload the property setter implementation to add our own logic
  37469. descriptor.set = function (val) {
  37470. // check for disposed first, do nothing
  37471. if (this.isDisposed) {
  37472. return;
  37473. }
  37474. var curVal = getter.call(this);
  37475. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  37476. return;
  37477. }
  37478. // Cast the object we're working one
  37479. var prim = this;
  37480. // Change the value
  37481. setter.call(this, val);
  37482. // Notify change, dirty flags update
  37483. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  37484. };
  37485. };
  37486. };
  37487. /**
  37488. * Add an externally attached data from its key.
  37489. * This method call will fail and return false, if such key already exists.
  37490. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  37491. * @param key the unique key that identifies the data
  37492. * @param data the data object to associate to the key for this Engine instance
  37493. * @return true if no such key were already present and the data was added successfully, false otherwise
  37494. */
  37495. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  37496. if (!this._externalData) {
  37497. this._externalData = new BABYLON.StringDictionary();
  37498. }
  37499. return this._externalData.add(key, data);
  37500. };
  37501. /**
  37502. * Get an externally attached data from its key
  37503. * @param key the unique key that identifies the data
  37504. * @return the associated data, if present (can be null), or undefined if not present
  37505. */
  37506. SmartPropertyPrim.prototype.getExternalData = function (key) {
  37507. if (!this._externalData) {
  37508. return null;
  37509. }
  37510. return this._externalData.get(key);
  37511. };
  37512. /**
  37513. * Get an externally attached data from its key, create it using a factory if it's not already present
  37514. * @param key the unique key that identifies the data
  37515. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  37516. * @return the associated data, can be null if the factory returned null.
  37517. */
  37518. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  37519. if (!this._externalData) {
  37520. this._externalData = new BABYLON.StringDictionary();
  37521. }
  37522. return this._externalData.getOrAddWithFactory(key, factory);
  37523. };
  37524. /**
  37525. * Remove an externally attached data from the Engine instance
  37526. * @param key the unique key that identifies the data
  37527. * @return true if the data was successfully removed, false if it doesn't exist
  37528. */
  37529. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  37530. if (!this._externalData) {
  37531. return false;
  37532. }
  37533. return this._externalData.remove(key);
  37534. };
  37535. /**
  37536. * Check if a given flag is set
  37537. * @param flag the flag value
  37538. * @return true if set, false otherwise
  37539. */
  37540. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  37541. return (this._flags & flag) !== 0;
  37542. };
  37543. /**
  37544. * Check if all given flags are set
  37545. * @param flags the flags ORed
  37546. * @return true if all the flags are set, false otherwise
  37547. */
  37548. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  37549. return (this._flags & flags) === flags;
  37550. };
  37551. /**
  37552. * Check if at least one flag of the given flags is set
  37553. * @param flags the flags ORed
  37554. * @return true if at least one flag is set, false otherwise
  37555. */
  37556. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  37557. return (this._flags & flags) !== 0;
  37558. };
  37559. /**
  37560. * Clear the given flags
  37561. * @param flags the flags to clear
  37562. */
  37563. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  37564. this._flags &= ~flags;
  37565. };
  37566. /**
  37567. * Set the given flags to true state
  37568. * @param flags the flags ORed to set
  37569. * @return the flags state before this call
  37570. */
  37571. SmartPropertyPrim.prototype._setFlags = function (flags) {
  37572. var cur = this._flags;
  37573. this._flags |= flags;
  37574. return cur;
  37575. };
  37576. /**
  37577. * Change the state of the given flags
  37578. * @param flags the flags ORed to change
  37579. * @param state true to set them, false to clear them
  37580. */
  37581. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  37582. if (state) {
  37583. this._flags |= flags;
  37584. }
  37585. else {
  37586. this._flags &= ~flags;
  37587. }
  37588. };
  37589. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  37590. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  37591. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  37592. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  37593. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  37594. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  37595. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  37596. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  37597. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  37598. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  37599. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  37600. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  37601. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  37602. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  37603. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  37604. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  37605. SmartPropertyPrim = __decorate([
  37606. BABYLON.className("SmartPropertyPrim")
  37607. ], SmartPropertyPrim);
  37608. return SmartPropertyPrim;
  37609. })();
  37610. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  37611. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37612. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37613. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37614. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37615. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  37616. }
  37617. BABYLON.modelLevelProperty = modelLevelProperty;
  37618. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37619. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37620. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37621. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37622. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  37623. }
  37624. BABYLON.instanceLevelProperty = instanceLevelProperty;
  37625. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  37626. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  37627. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  37628. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  37629. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  37630. }
  37631. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  37632. })(BABYLON || (BABYLON = {}));
  37633. var BABYLON;
  37634. (function (BABYLON) {
  37635. var PrepareRender2DContext = (function () {
  37636. function PrepareRender2DContext() {
  37637. this.forceRefreshPrimitive = false;
  37638. }
  37639. return PrepareRender2DContext;
  37640. })();
  37641. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  37642. var Render2DContext = (function () {
  37643. function Render2DContext(renderMode) {
  37644. this._renderMode = renderMode;
  37645. this.useInstancing = false;
  37646. this.groupInfoPartData = null;
  37647. this.partDataStartIndex = this.partDataEndIndex = null;
  37648. this.instancedBuffers = null;
  37649. }
  37650. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  37651. /**
  37652. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  37653. */
  37654. get: function () {
  37655. return this._renderMode;
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  37661. /**
  37662. * The set of primitives to render is opaque.
  37663. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  37664. */
  37665. get: function () {
  37666. return Render2DContext._renderModeOpaque;
  37667. },
  37668. enumerable: true,
  37669. configurable: true
  37670. });
  37671. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  37672. /**
  37673. * The set of primitives to render is using Alpha Test (aka masking).
  37674. * 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.
  37675. */
  37676. get: function () {
  37677. return Render2DContext._renderModeAlphaTest;
  37678. },
  37679. enumerable: true,
  37680. configurable: true
  37681. });
  37682. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  37683. /**
  37684. * The set of primitives to render is transparent.
  37685. * 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.
  37686. */
  37687. get: function () {
  37688. return Render2DContext._renderModeTransparent;
  37689. },
  37690. enumerable: true,
  37691. configurable: true
  37692. });
  37693. Render2DContext._renderModeOpaque = 1;
  37694. Render2DContext._renderModeAlphaTest = 2;
  37695. Render2DContext._renderModeTransparent = 3;
  37696. return Render2DContext;
  37697. })();
  37698. BABYLON.Render2DContext = Render2DContext;
  37699. /**
  37700. * This class store information for the pointerEventObservable Observable.
  37701. * 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.
  37702. */
  37703. var PrimitivePointerInfo = (function () {
  37704. function PrimitivePointerInfo() {
  37705. this.primitivePointerPos = BABYLON.Vector2.Zero();
  37706. this.tilt = BABYLON.Vector2.Zero();
  37707. this.cancelBubble = false;
  37708. }
  37709. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  37710. // 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.
  37711. /**
  37712. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  37713. * Bubbles: yes
  37714. */
  37715. get: function () {
  37716. return PrimitivePointerInfo._pointerOver;
  37717. },
  37718. enumerable: true,
  37719. configurable: true
  37720. });
  37721. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  37722. /**
  37723. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  37724. * Bubbles: no
  37725. */
  37726. get: function () {
  37727. return PrimitivePointerInfo._pointerEnter;
  37728. },
  37729. enumerable: true,
  37730. configurable: true
  37731. });
  37732. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  37733. /**
  37734. * 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.
  37735. * Bubbles: yes
  37736. */
  37737. get: function () {
  37738. return PrimitivePointerInfo._pointerDown;
  37739. },
  37740. enumerable: true,
  37741. configurable: true
  37742. });
  37743. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  37744. /**
  37745. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  37746. * Bubbles: yes
  37747. */
  37748. get: function () {
  37749. return PrimitivePointerInfo._pointerMouseWheel;
  37750. },
  37751. enumerable: true,
  37752. configurable: true
  37753. });
  37754. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  37755. /**
  37756. * 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.
  37757. * Bubbles: yes
  37758. */
  37759. get: function () {
  37760. return PrimitivePointerInfo._pointerMove;
  37761. },
  37762. enumerable: true,
  37763. configurable: true
  37764. });
  37765. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  37766. /**
  37767. * 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.
  37768. * Bubbles: yes
  37769. */
  37770. get: function () {
  37771. return PrimitivePointerInfo._pointerUp;
  37772. },
  37773. enumerable: true,
  37774. configurable: true
  37775. });
  37776. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  37777. /**
  37778. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  37779. * Bubbles: yes
  37780. */
  37781. get: function () {
  37782. return PrimitivePointerInfo._pointerOut;
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  37788. /**
  37789. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  37790. * Bubbles: no
  37791. */
  37792. get: function () {
  37793. return PrimitivePointerInfo._pointerLeave;
  37794. },
  37795. enumerable: true,
  37796. configurable: true
  37797. });
  37798. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  37799. /**
  37800. * 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.
  37801. * Bubbles: yes
  37802. */
  37803. get: function () {
  37804. return PrimitivePointerInfo._pointerGotCapture;
  37805. },
  37806. enumerable: true,
  37807. configurable: true
  37808. });
  37809. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  37810. /**
  37811. * This event type is raised after pointer capture is released for a pointer.
  37812. * Bubbles: yes
  37813. */
  37814. get: function () {
  37815. return PrimitivePointerInfo._pointerLostCapture;
  37816. },
  37817. enumerable: true,
  37818. configurable: true
  37819. });
  37820. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  37821. get: function () {
  37822. return PrimitivePointerInfo._mouseWheelPrecision;
  37823. },
  37824. enumerable: true,
  37825. configurable: true
  37826. });
  37827. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  37828. this.relatedTarget = prim;
  37829. this.relatedTargetPointerPos = primPointerPos;
  37830. };
  37831. PrimitivePointerInfo.getEventTypeName = function (mask) {
  37832. switch (mask) {
  37833. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  37834. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  37835. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  37836. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  37837. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  37838. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  37839. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  37840. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  37841. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  37842. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  37843. }
  37844. };
  37845. PrimitivePointerInfo._pointerOver = 0x0001;
  37846. PrimitivePointerInfo._pointerEnter = 0x0002;
  37847. PrimitivePointerInfo._pointerDown = 0x0004;
  37848. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  37849. PrimitivePointerInfo._pointerMove = 0x0010;
  37850. PrimitivePointerInfo._pointerUp = 0x0020;
  37851. PrimitivePointerInfo._pointerOut = 0x0040;
  37852. PrimitivePointerInfo._pointerLeave = 0x0080;
  37853. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  37854. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  37855. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  37856. return PrimitivePointerInfo;
  37857. })();
  37858. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  37859. /**
  37860. * Defines the horizontal and vertical alignment information for a Primitive.
  37861. */
  37862. var PrimitiveAlignment = (function () {
  37863. function PrimitiveAlignment(changeCallback) {
  37864. this._changedCallback = changeCallback;
  37865. this._horizontal = PrimitiveAlignment.AlignLeft;
  37866. this._vertical = PrimitiveAlignment.AlignBottom;
  37867. }
  37868. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  37869. /**
  37870. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  37871. */
  37872. get: function () { return PrimitiveAlignment._AlignLeft; },
  37873. enumerable: true,
  37874. configurable: true
  37875. });
  37876. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  37877. /**
  37878. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  37879. */
  37880. get: function () { return PrimitiveAlignment._AlignTop; },
  37881. enumerable: true,
  37882. configurable: true
  37883. });
  37884. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  37885. /**
  37886. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  37887. */
  37888. get: function () { return PrimitiveAlignment._AlignRight; },
  37889. enumerable: true,
  37890. configurable: true
  37891. });
  37892. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  37893. /**
  37894. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  37895. */
  37896. get: function () { return PrimitiveAlignment._AlignBottom; },
  37897. enumerable: true,
  37898. configurable: true
  37899. });
  37900. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  37901. /**
  37902. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  37903. */
  37904. get: function () { return PrimitiveAlignment._AlignCenter; },
  37905. enumerable: true,
  37906. configurable: true
  37907. });
  37908. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  37909. /**
  37910. * The content is stretched toward the opposite edges of the Primitive
  37911. */
  37912. get: function () { return PrimitiveAlignment._AlignStretch; },
  37913. enumerable: true,
  37914. configurable: true
  37915. });
  37916. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  37917. /**
  37918. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  37919. */
  37920. get: function () {
  37921. return this._horizontal;
  37922. },
  37923. set: function (value) {
  37924. if (this._horizontal === value) {
  37925. return;
  37926. }
  37927. this._horizontal = value;
  37928. this._changedCallback();
  37929. },
  37930. enumerable: true,
  37931. configurable: true
  37932. });
  37933. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  37934. /**
  37935. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  37936. */
  37937. get: function () {
  37938. return this._vertical;
  37939. },
  37940. set: function (value) {
  37941. if (this._vertical === value) {
  37942. return;
  37943. }
  37944. this._vertical = value;
  37945. this._changedCallback();
  37946. },
  37947. enumerable: true,
  37948. configurable: true
  37949. });
  37950. /**
  37951. * Set the horizontal alignment from a string value.
  37952. * @param text can be either: 'left','right','center','stretch'
  37953. */
  37954. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  37955. var v = text.trim().toLocaleLowerCase();
  37956. switch (v) {
  37957. case "left":
  37958. this.horizontal = PrimitiveAlignment.AlignLeft;
  37959. return;
  37960. case "right":
  37961. this.horizontal = PrimitiveAlignment.AlignRight;
  37962. return;
  37963. case "center":
  37964. this.horizontal = PrimitiveAlignment.AlignCenter;
  37965. return;
  37966. case "stretch":
  37967. this.horizontal = PrimitiveAlignment.AlignStretch;
  37968. return;
  37969. }
  37970. };
  37971. /**
  37972. * Set the vertical alignment from a string value.
  37973. * @param text can be either: 'top','bottom','center','stretch'
  37974. */
  37975. PrimitiveAlignment.prototype.setVertical = function (text) {
  37976. var v = text.trim().toLocaleLowerCase();
  37977. switch (v) {
  37978. case "top":
  37979. this.vertical = PrimitiveAlignment.AlignTop;
  37980. return;
  37981. case "bottom":
  37982. this.vertical = PrimitiveAlignment.AlignBottom;
  37983. return;
  37984. case "center":
  37985. this.vertical = PrimitiveAlignment.AlignCenter;
  37986. return;
  37987. case "stretch":
  37988. this.vertical = PrimitiveAlignment.AlignStretch;
  37989. return;
  37990. }
  37991. };
  37992. /**
  37993. * Set the horizontal and or vertical alignments from a string value.
  37994. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  37995. */
  37996. PrimitiveAlignment.prototype.fromString = function (value) {
  37997. var m = value.trim().split(",");
  37998. for (var _i = 0; _i < m.length; _i++) {
  37999. var v = m[_i];
  38000. v = v.toLocaleLowerCase().trim();
  38001. // Horizontal
  38002. var i = v.indexOf("h:");
  38003. if (i === -1) {
  38004. i = v.indexOf("horizontal:");
  38005. }
  38006. if (i !== -1) {
  38007. v = v.substr(v.indexOf(":") + 1);
  38008. this.setHorizontal(v);
  38009. continue;
  38010. }
  38011. // Vertical
  38012. i = v.indexOf("v:");
  38013. if (i === -1) {
  38014. i = v.indexOf("vertical:");
  38015. }
  38016. if (i !== -1) {
  38017. v = v.substr(v.indexOf(":") + 1);
  38018. this.setVertical(v);
  38019. continue;
  38020. }
  38021. }
  38022. };
  38023. PrimitiveAlignment._AlignLeft = 1;
  38024. PrimitiveAlignment._AlignTop = 1; // Same as left
  38025. PrimitiveAlignment._AlignRight = 2;
  38026. PrimitiveAlignment._AlignBottom = 2; // Same as right
  38027. PrimitiveAlignment._AlignCenter = 3;
  38028. PrimitiveAlignment._AlignStretch = 4;
  38029. return PrimitiveAlignment;
  38030. })();
  38031. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  38032. /**
  38033. * Stores information about a Primitive that was intersected
  38034. */
  38035. var PrimitiveIntersectedInfo = (function () {
  38036. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  38037. this.prim = prim;
  38038. this.intersectionLocation = intersectionLocation;
  38039. }
  38040. return PrimitiveIntersectedInfo;
  38041. })();
  38042. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  38043. /**
  38044. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  38045. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  38046. */
  38047. var PrimitiveThickness = (function () {
  38048. function PrimitiveThickness(parentAccess, changedCallback) {
  38049. this._parentAccess = parentAccess;
  38050. this._changedCallback = changedCallback;
  38051. this._pixels = new Array(4);
  38052. this._percentages = new Array(4);
  38053. this._setType(0, PrimitiveThickness.Auto);
  38054. this._setType(1, PrimitiveThickness.Auto);
  38055. this._setType(2, PrimitiveThickness.Auto);
  38056. this._setType(3, PrimitiveThickness.Auto);
  38057. this._pixels[0] = 0;
  38058. this._pixels[1] = 0;
  38059. this._pixels[2] = 0;
  38060. this._pixels[3] = 0;
  38061. }
  38062. /**
  38063. * Set the thickness from a string value
  38064. * @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.
  38065. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38066. */
  38067. PrimitiveThickness.prototype.fromString = function (thickness) {
  38068. this._clear();
  38069. var m = thickness.trim().split(",");
  38070. // Special case, one value to apply to all edges
  38071. if (m.length === 1 && thickness.indexOf(":") === -1) {
  38072. this._setStringValue(m[0], 0, false);
  38073. this._setStringValue(m[0], 1, false);
  38074. this._setStringValue(m[0], 2, false);
  38075. this._setStringValue(m[0], 3, false);
  38076. this._changedCallback();
  38077. return;
  38078. }
  38079. var res = false;
  38080. for (var _i = 0; _i < m.length; _i++) {
  38081. var cm = m[_i];
  38082. res = this._extractString(cm, false) || res;
  38083. }
  38084. if (!res) {
  38085. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  38086. }
  38087. // Check the margin that weren't set and set them in auto
  38088. if ((this._flags & 0x000F) === 0)
  38089. this._flags |= PrimitiveThickness.Pixel << 0;
  38090. if ((this._flags & 0x00F0) === 0)
  38091. this._flags |= PrimitiveThickness.Pixel << 4;
  38092. if ((this._flags & 0x0F00) === 0)
  38093. this._flags |= PrimitiveThickness.Pixel << 8;
  38094. if ((this._flags & 0xF000) === 0)
  38095. this._flags |= PrimitiveThickness.Pixel << 12;
  38096. this._changedCallback();
  38097. };
  38098. /**
  38099. * Set the thickness from multiple string
  38100. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38101. * @param top the top thickness to set
  38102. * @param left the left thickness to set
  38103. * @param right the right thickness to set
  38104. * @param bottom the bottom thickness to set
  38105. */
  38106. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  38107. this._clear();
  38108. this._setStringValue(top, 0, false);
  38109. this._setStringValue(left, 1, false);
  38110. this._setStringValue(right, 2, false);
  38111. this._setStringValue(bottom, 3, false);
  38112. this._changedCallback();
  38113. return this;
  38114. };
  38115. /**
  38116. * Set the thickness from pixel values
  38117. * @param top the top thickness in pixels to set
  38118. * @param left the left thickness in pixels to set
  38119. * @param right the right thickness in pixels to set
  38120. * @param bottom the bottom thickness in pixels to set
  38121. */
  38122. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  38123. this._clear();
  38124. this._pixels[0] = top;
  38125. this._pixels[1] = left;
  38126. this._pixels[2] = right;
  38127. this._pixels[3] = bottom;
  38128. this._changedCallback();
  38129. return this;
  38130. };
  38131. /**
  38132. * Apply the same pixel value to all edges
  38133. * @param margin the value to set, in pixels.
  38134. */
  38135. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  38136. this._clear();
  38137. this._pixels[0] = margin;
  38138. this._pixels[1] = margin;
  38139. this._pixels[2] = margin;
  38140. this._pixels[3] = margin;
  38141. this._changedCallback();
  38142. return this;
  38143. };
  38144. /**
  38145. * Set all edges in auto
  38146. */
  38147. PrimitiveThickness.prototype.auto = function () {
  38148. this._clear();
  38149. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  38150. this._pixels[0] = 0;
  38151. this._pixels[1] = 0;
  38152. this._pixels[2] = 0;
  38153. this._pixels[3] = 0;
  38154. this._changedCallback();
  38155. return this;
  38156. };
  38157. PrimitiveThickness.prototype._clear = function () {
  38158. this._flags = 0;
  38159. this._pixels[0] = 0;
  38160. this._pixels[1] = 0;
  38161. this._pixels[2] = 0;
  38162. this._pixels[3] = 0;
  38163. this._percentages[0] = null;
  38164. this._percentages[1] = null;
  38165. this._percentages[2] = null;
  38166. this._percentages[3] = null;
  38167. };
  38168. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  38169. var v = value.trim().toLocaleLowerCase();
  38170. if (v.indexOf("top:") === 0) {
  38171. v = v.substr(4).trim();
  38172. return this._setStringValue(v, 0, emitChanged);
  38173. }
  38174. if (v.indexOf("left:") === 0) {
  38175. v = v.substr(5).trim();
  38176. return this._setStringValue(v, 1, emitChanged);
  38177. }
  38178. if (v.indexOf("right:") === 0) {
  38179. v = v.substr(6).trim();
  38180. return this._setStringValue(v, 2, emitChanged);
  38181. }
  38182. if (v.indexOf("bottom:") === 0) {
  38183. v = v.substr(7).trim();
  38184. return this._setStringValue(v, 3, emitChanged);
  38185. }
  38186. return false;
  38187. };
  38188. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  38189. // Check for auto
  38190. var v = value.trim().toLocaleLowerCase();
  38191. if (v === "auto") {
  38192. if (this._isType(index, PrimitiveThickness.Auto)) {
  38193. return true;
  38194. }
  38195. this._setType(index, PrimitiveThickness.Auto);
  38196. this._pixels[index] = 0;
  38197. if (emitChanged) {
  38198. this._changedCallback();
  38199. }
  38200. }
  38201. else if (v === "inherit") {
  38202. if (this._isType(index, PrimitiveThickness.Inherit)) {
  38203. return true;
  38204. }
  38205. this._setType(index, PrimitiveThickness.Inherit);
  38206. this._pixels[index] = null;
  38207. if (emitChanged) {
  38208. this._changedCallback();
  38209. }
  38210. }
  38211. else {
  38212. var pI = v.indexOf("%");
  38213. // Check for percentage
  38214. if (pI !== -1) {
  38215. var n_1 = v.substr(0, pI);
  38216. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  38217. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  38218. return true;
  38219. }
  38220. this._setType(index, PrimitiveThickness.Percentage);
  38221. if (isNaN(number_1)) {
  38222. return false;
  38223. }
  38224. this._percentages[index] = number_1;
  38225. if (emitChanged) {
  38226. this._changedCallback();
  38227. }
  38228. return true;
  38229. }
  38230. // Check for pixel
  38231. var n;
  38232. pI = v.indexOf("px");
  38233. if (pI !== -1) {
  38234. n = v.substr(0, pI).trim();
  38235. }
  38236. else {
  38237. n = v;
  38238. }
  38239. var number = Number(n);
  38240. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  38241. return true;
  38242. }
  38243. if (isNaN(number)) {
  38244. return false;
  38245. }
  38246. this._pixels[index] = number;
  38247. this._setType(index, PrimitiveThickness.Pixel);
  38248. if (emitChanged) {
  38249. this._changedCallback();
  38250. }
  38251. return true;
  38252. }
  38253. };
  38254. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  38255. // 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
  38256. value = Math.round(value);
  38257. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  38258. return;
  38259. }
  38260. this._setType(index, PrimitiveThickness.Pixel);
  38261. this._pixels[index] = value;
  38262. if (emitChanged) {
  38263. this._changedCallback();
  38264. }
  38265. };
  38266. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  38267. // Clip Value to bounds
  38268. value = Math.min(1, value);
  38269. value = Math.max(0, value);
  38270. value = Math.round(value * 100) / 100; // 0.01 precision
  38271. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  38272. return;
  38273. }
  38274. this._setType(index, PrimitiveThickness.Percentage);
  38275. this._percentages[index] = value;
  38276. if (emitChanged) {
  38277. this._changedCallback();
  38278. }
  38279. };
  38280. PrimitiveThickness.prototype._getStringValue = function (index) {
  38281. var f = (this._flags >> (index * 4)) & 0xF;
  38282. switch (f) {
  38283. case PrimitiveThickness.Auto:
  38284. return "auto";
  38285. case PrimitiveThickness.Pixel:
  38286. return this._pixels[index] + "px";
  38287. case PrimitiveThickness.Percentage:
  38288. return this._percentages[index] * 100 + "%";
  38289. case PrimitiveThickness.Inherit:
  38290. return "inherit";
  38291. }
  38292. return "";
  38293. };
  38294. PrimitiveThickness.prototype._isType = function (index, type) {
  38295. var f = (this._flags >> (index * 4)) & 0xF;
  38296. return f === type;
  38297. };
  38298. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  38299. var t = (this._flags >> (index * 4)) & 0xF;
  38300. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  38301. var p = this._parentAccess();
  38302. if (p) {
  38303. return p._getType(index, true);
  38304. }
  38305. return PrimitiveThickness.Auto;
  38306. }
  38307. return t;
  38308. };
  38309. PrimitiveThickness.prototype._setType = function (index, type) {
  38310. this._flags &= ~(0xF << (index * 4));
  38311. this._flags |= type << (index * 4);
  38312. };
  38313. PrimitiveThickness.prototype.setTop = function (value) {
  38314. if (typeof value === "string") {
  38315. this._setStringValue(value, 0, true);
  38316. }
  38317. else {
  38318. this.topPixels = value;
  38319. }
  38320. };
  38321. PrimitiveThickness.prototype.setLeft = function (value) {
  38322. if (typeof value === "string") {
  38323. this._setStringValue(value, 1, true);
  38324. }
  38325. else {
  38326. this.leftPixels = value;
  38327. }
  38328. };
  38329. PrimitiveThickness.prototype.setRight = function (value) {
  38330. if (typeof value === "string") {
  38331. this._setStringValue(value, 2, true);
  38332. }
  38333. else {
  38334. this.rightPixels = value;
  38335. }
  38336. };
  38337. PrimitiveThickness.prototype.setBottom = function (value) {
  38338. if (typeof value === "string") {
  38339. this._setStringValue(value, 3, true);
  38340. }
  38341. else {
  38342. this.bottomPixels = value;
  38343. }
  38344. };
  38345. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  38346. /**
  38347. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38348. */
  38349. get: function () {
  38350. return this._getStringValue(0);
  38351. },
  38352. set: function (value) {
  38353. this._setStringValue(value, 0, true);
  38354. },
  38355. enumerable: true,
  38356. configurable: true
  38357. });
  38358. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  38359. /**
  38360. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38361. */
  38362. get: function () {
  38363. return this._getStringValue(1);
  38364. },
  38365. set: function (value) {
  38366. this._setStringValue(value, 1, true);
  38367. },
  38368. enumerable: true,
  38369. configurable: true
  38370. });
  38371. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  38372. /**
  38373. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38374. */
  38375. get: function () {
  38376. return this._getStringValue(2);
  38377. },
  38378. set: function (value) {
  38379. this._setStringValue(value, 2, true);
  38380. },
  38381. enumerable: true,
  38382. configurable: true
  38383. });
  38384. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  38385. /**
  38386. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  38387. */
  38388. get: function () {
  38389. return this._getStringValue(3);
  38390. },
  38391. set: function (value) {
  38392. this._setStringValue(value, 3, true);
  38393. },
  38394. enumerable: true,
  38395. configurable: true
  38396. });
  38397. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  38398. /**
  38399. * Get/set the top thickness in pixel.
  38400. */
  38401. get: function () {
  38402. return this._pixels[0];
  38403. },
  38404. set: function (value) {
  38405. this._setPixels(value, 0, true);
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  38411. /**
  38412. * Get/set the left thickness in pixel.
  38413. */
  38414. get: function () {
  38415. return this._pixels[1];
  38416. },
  38417. set: function (value) {
  38418. this._setPixels(value, 1, true);
  38419. },
  38420. enumerable: true,
  38421. configurable: true
  38422. });
  38423. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  38424. /**
  38425. * Get/set the right thickness in pixel.
  38426. */
  38427. get: function () {
  38428. return this._pixels[2];
  38429. },
  38430. set: function (value) {
  38431. this._setPixels(value, 2, true);
  38432. },
  38433. enumerable: true,
  38434. configurable: true
  38435. });
  38436. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  38437. /**
  38438. * Get/set the bottom thickness in pixel.
  38439. */
  38440. get: function () {
  38441. return this._pixels[3];
  38442. },
  38443. set: function (value) {
  38444. this._setPixels(value, 3, true);
  38445. },
  38446. enumerable: true,
  38447. configurable: true
  38448. });
  38449. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  38450. /**
  38451. * Get/set the top thickness in percentage.
  38452. * The get will return a valid value only if the edge type is percentage.
  38453. * The Set will change the edge mode if needed
  38454. */
  38455. get: function () {
  38456. return this._percentages[0];
  38457. },
  38458. set: function (value) {
  38459. this._setPercentage(value, 0, true);
  38460. },
  38461. enumerable: true,
  38462. configurable: true
  38463. });
  38464. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  38465. /**
  38466. * Get/set the left thickness in percentage.
  38467. * The get will return a valid value only if the edge mode is percentage.
  38468. * The Set will change the edge mode if needed
  38469. */
  38470. get: function () {
  38471. return this._percentages[1];
  38472. },
  38473. set: function (value) {
  38474. this._setPercentage(value, 1, true);
  38475. },
  38476. enumerable: true,
  38477. configurable: true
  38478. });
  38479. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  38480. /**
  38481. * Get/set the right thickness in percentage.
  38482. * The get will return a valid value only if the edge mode is percentage.
  38483. * The Set will change the edge mode if needed
  38484. */
  38485. get: function () {
  38486. return this._percentages[2];
  38487. },
  38488. set: function (value) {
  38489. this._setPercentage(value, 2, true);
  38490. },
  38491. enumerable: true,
  38492. configurable: true
  38493. });
  38494. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  38495. /**
  38496. * Get/set the bottom thickness in percentage.
  38497. * The get will return a valid value only if the edge mode is percentage.
  38498. * The Set will change the edge mode if needed
  38499. */
  38500. get: function () {
  38501. return this._percentages[3];
  38502. },
  38503. set: function (value) {
  38504. this._setPercentage(value, 3, true);
  38505. },
  38506. enumerable: true,
  38507. configurable: true
  38508. });
  38509. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  38510. /**
  38511. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  38512. */
  38513. get: function () {
  38514. return this._getType(0, false);
  38515. },
  38516. set: function (mode) {
  38517. this._setType(0, mode);
  38518. },
  38519. enumerable: true,
  38520. configurable: true
  38521. });
  38522. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  38523. /**
  38524. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  38525. */
  38526. get: function () {
  38527. return this._getType(1, false);
  38528. },
  38529. set: function (mode) {
  38530. this._setType(1, mode);
  38531. },
  38532. enumerable: true,
  38533. configurable: true
  38534. });
  38535. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  38536. /**
  38537. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  38538. */
  38539. get: function () {
  38540. return this._getType(2, false);
  38541. },
  38542. set: function (mode) {
  38543. this._setType(2, mode);
  38544. },
  38545. enumerable: true,
  38546. configurable: true
  38547. });
  38548. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  38549. /**
  38550. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  38551. */
  38552. get: function () {
  38553. return this._getType(3, false);
  38554. },
  38555. set: function (mode) {
  38556. this._setType(3, mode);
  38557. },
  38558. enumerable: true,
  38559. configurable: true
  38560. });
  38561. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  38562. var type = this._getType(index, false);
  38563. if (type === PrimitiveThickness.Inherit) {
  38564. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  38565. return;
  38566. }
  38567. if (type !== PrimitiveThickness.Percentage) {
  38568. return;
  38569. }
  38570. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  38571. this._pixels[index] = pixels;
  38572. if (emitChanged) {
  38573. this._changedCallback();
  38574. }
  38575. };
  38576. /**
  38577. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  38578. * @param sourceArea the source area
  38579. * @param contentSize the content size to position/resize
  38580. * @param alignment the alignment setting
  38581. * @param dstOffset the position of the content
  38582. * @param dstArea the new size of the content
  38583. */
  38584. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  38585. // Fetch some data
  38586. var topType = this._getType(0, true);
  38587. var leftType = this._getType(1, true);
  38588. var rightType = this._getType(2, true);
  38589. var bottomType = this._getType(3, true);
  38590. var hasWidth = contentSize && (contentSize.width != null);
  38591. var hasHeight = contentSize && (contentSize.height != null);
  38592. var width = hasWidth ? contentSize.width : 0;
  38593. var height = hasHeight ? contentSize.height : 0;
  38594. var isTopAuto = topType === PrimitiveThickness.Auto;
  38595. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  38596. var isRightAuto = rightType === PrimitiveThickness.Auto;
  38597. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  38598. switch (alignment.horizontal) {
  38599. case PrimitiveAlignment.AlignLeft:
  38600. {
  38601. if (isLeftAuto) {
  38602. dstOffset.x = 0;
  38603. }
  38604. else {
  38605. this._computePixels(1, sourceArea, true);
  38606. dstOffset.x = this.leftPixels;
  38607. }
  38608. dstArea.width = width;
  38609. break;
  38610. }
  38611. case PrimitiveAlignment.AlignRight:
  38612. {
  38613. if (isRightAuto) {
  38614. dstOffset.x = Math.round(sourceArea.width - width);
  38615. }
  38616. else {
  38617. this._computePixels(2, sourceArea, true);
  38618. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  38619. }
  38620. dstArea.width = width;
  38621. break;
  38622. }
  38623. case PrimitiveAlignment.AlignStretch:
  38624. {
  38625. if (isLeftAuto) {
  38626. dstOffset.x = 0;
  38627. }
  38628. else {
  38629. this._computePixels(1, sourceArea, true);
  38630. dstOffset.x = this.leftPixels;
  38631. }
  38632. var right = 0;
  38633. if (!isRightAuto) {
  38634. this._computePixels(2, sourceArea, true);
  38635. right = this.rightPixels;
  38636. }
  38637. dstArea.width = sourceArea.width - (dstOffset.x + right);
  38638. break;
  38639. }
  38640. case PrimitiveAlignment.AlignCenter:
  38641. {
  38642. if (!isLeftAuto) {
  38643. this._computePixels(1, sourceArea, true);
  38644. }
  38645. if (!isRightAuto) {
  38646. this._computePixels(2, sourceArea, true);
  38647. }
  38648. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  38649. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  38650. dstArea.width = width;
  38651. break;
  38652. }
  38653. }
  38654. switch (alignment.vertical) {
  38655. case PrimitiveAlignment.AlignTop:
  38656. {
  38657. if (isTopAuto) {
  38658. dstOffset.y = sourceArea.height - height;
  38659. }
  38660. else {
  38661. this._computePixels(0, sourceArea, true);
  38662. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  38663. }
  38664. dstArea.height = height;
  38665. break;
  38666. }
  38667. case PrimitiveAlignment.AlignBottom:
  38668. {
  38669. if (isBottomAuto) {
  38670. dstOffset.y = 0;
  38671. }
  38672. else {
  38673. this._computePixels(3, sourceArea, true);
  38674. dstOffset.y = this.bottomPixels;
  38675. }
  38676. dstArea.height = height;
  38677. break;
  38678. }
  38679. case PrimitiveAlignment.AlignStretch:
  38680. {
  38681. if (isBottomAuto) {
  38682. dstOffset.y = 0;
  38683. }
  38684. else {
  38685. this._computePixels(3, sourceArea, true);
  38686. dstOffset.y = this.bottomPixels;
  38687. }
  38688. var top_1 = 0;
  38689. if (!isTopAuto) {
  38690. this._computePixels(0, sourceArea, true);
  38691. top_1 = this.topPixels;
  38692. }
  38693. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  38694. break;
  38695. }
  38696. case PrimitiveAlignment.AlignCenter:
  38697. {
  38698. if (!isTopAuto) {
  38699. this._computePixels(0, sourceArea, true);
  38700. }
  38701. if (!isBottomAuto) {
  38702. this._computePixels(3, sourceArea, true);
  38703. }
  38704. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  38705. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  38706. dstArea.height = height;
  38707. break;
  38708. }
  38709. }
  38710. };
  38711. /**
  38712. * Compute an area and its position considering this thickness properties based on a given source area
  38713. * @param sourceArea the source area
  38714. * @param dstOffset the position of the resulting area
  38715. * @param dstArea the size of the resulting area
  38716. */
  38717. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  38718. this._computePixels(0, sourceArea, true);
  38719. this._computePixels(1, sourceArea, true);
  38720. this._computePixels(2, sourceArea, true);
  38721. this._computePixels(3, sourceArea, true);
  38722. dstOffset.x = this.leftPixels;
  38723. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  38724. dstOffset.y = this.bottomPixels;
  38725. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  38726. };
  38727. /**
  38728. * Compute an area considering this thickness properties based on a given source area
  38729. * @param sourceArea the source area
  38730. * @param result the resulting area
  38731. */
  38732. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  38733. this._computePixels(0, sourceArea, true);
  38734. this._computePixels(1, sourceArea, true);
  38735. this._computePixels(2, sourceArea, true);
  38736. this._computePixels(3, sourceArea, true);
  38737. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  38738. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  38739. };
  38740. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  38741. this._computePixels(0, sourceArea, true);
  38742. this._computePixels(1, sourceArea, true);
  38743. this._computePixels(2, sourceArea, true);
  38744. this._computePixels(3, sourceArea, true);
  38745. dstOffset.x = this.leftPixels;
  38746. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  38747. dstOffset.y = this.bottomPixels;
  38748. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  38749. };
  38750. PrimitiveThickness.Auto = 0x1;
  38751. PrimitiveThickness.Inherit = 0x2;
  38752. PrimitiveThickness.Percentage = 0x4;
  38753. PrimitiveThickness.Pixel = 0x8;
  38754. return PrimitiveThickness;
  38755. })();
  38756. BABYLON.PrimitiveThickness = PrimitiveThickness;
  38757. /**
  38758. * Main class used for the Primitive Intersection API
  38759. */
  38760. var IntersectInfo2D = (function () {
  38761. function IntersectInfo2D() {
  38762. this.findFirstOnly = false;
  38763. this.intersectHidden = false;
  38764. this.pickPosition = BABYLON.Vector2.Zero();
  38765. }
  38766. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  38767. /**
  38768. * true if at least one primitive intersected during the test
  38769. */
  38770. get: function () {
  38771. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  38772. },
  38773. enumerable: true,
  38774. configurable: true
  38775. });
  38776. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  38777. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  38778. var cur = _a[_i];
  38779. if (cur.prim === prim) {
  38780. return cur.intersectionLocation;
  38781. }
  38782. }
  38783. return null;
  38784. };
  38785. // Internals, don't use
  38786. IntersectInfo2D.prototype._exit = function (firstLevel) {
  38787. if (firstLevel) {
  38788. this._globalPickPosition = null;
  38789. }
  38790. };
  38791. return IntersectInfo2D;
  38792. })();
  38793. BABYLON.IntersectInfo2D = IntersectInfo2D;
  38794. var Prim2DBase = (function (_super) {
  38795. __extends(Prim2DBase, _super);
  38796. function Prim2DBase(settings) {
  38797. // Avoid checking every time if the object exists
  38798. if (settings == null) {
  38799. settings = {};
  38800. }
  38801. // BASE CLASS CALL
  38802. _super.call(this);
  38803. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  38804. var owner;
  38805. var parent;
  38806. if (Prim2DBase._isCanvasInit) {
  38807. owner = this;
  38808. parent = null;
  38809. this._canvasPreInit(settings);
  38810. }
  38811. else {
  38812. if (settings.parent != null) {
  38813. parent = settings.parent;
  38814. owner = settings.parent.owner;
  38815. if (!owner) {
  38816. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  38817. }
  38818. 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)) {
  38819. 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");
  38820. }
  38821. }
  38822. }
  38823. // Fields initialization
  38824. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38825. this._size = null; //Size.Zero();
  38826. this._actualSize = null;
  38827. this._boundingSize = BABYLON.Size.Zero();
  38828. this._layoutArea = BABYLON.Size.Zero();
  38829. this._layoutAreaPos = BABYLON.Vector2.Zero();
  38830. this._marginOffset = BABYLON.Vector2.Zero();
  38831. this._paddingOffset = BABYLON.Vector2.Zero();
  38832. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  38833. this._parentContentArea = BABYLON.Size.Zero();
  38834. this._lastAutoSizeArea = BABYLON.Size.Zero();
  38835. this._contentArea = new BABYLON.Size(null, null);
  38836. this._pointerEventObservable = new BABYLON.Observable();
  38837. this._boundingInfo = new BABYLON.BoundingInfo2D();
  38838. this._owner = owner;
  38839. this._parent = null;
  38840. this._margin = null;
  38841. this._padding = null;
  38842. this._marginAlignment = null;
  38843. this._id = settings.id;
  38844. this.propertyChanged = new BABYLON.Observable();
  38845. this._children = new Array();
  38846. this._localTransform = new BABYLON.Matrix();
  38847. this._globalTransform = null;
  38848. this._invGlobalTransform = null;
  38849. this._globalTransformProcessStep = 0;
  38850. this._globalTransformStep = 0;
  38851. this._renderGroup = null;
  38852. this._primLinearPosition = 0;
  38853. this._manualZOrder = null;
  38854. this._zOrder = 0;
  38855. this._zMax = 0;
  38856. this._firstZDirtyIndex = Prim2DBase._bigInt;
  38857. this._setFlags(BABYLON.SmartPropertyPrim.flagIsPickable | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  38858. if (settings.opacity != null) {
  38859. this._opacity = settings.opacity;
  38860. }
  38861. else {
  38862. this._opacity = 1;
  38863. }
  38864. if (settings.childrenFlatZOrder) {
  38865. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  38866. }
  38867. // If the parent is given, initialize the hierarchy/owner related data
  38868. if (parent != null) {
  38869. parent.addChild(this);
  38870. this._patchHierarchy(parent.owner);
  38871. }
  38872. // If it's a group, detect its own states
  38873. if (this.owner && this instanceof BABYLON.Group2D) {
  38874. var group = this;
  38875. group.detectGroupStates();
  38876. }
  38877. // Time to insert children if some are specified
  38878. if (settings.children != null) {
  38879. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  38880. var child = _a[_i];
  38881. this.addChild(child);
  38882. // Good time to patch the hierarchy, it won't go very far if there's no need to
  38883. child._patchHierarchy(this.owner);
  38884. }
  38885. }
  38886. // Set the model related properties
  38887. if (settings.position != null) {
  38888. this.position = settings.position;
  38889. }
  38890. else if (settings.x != null || settings.y != null) {
  38891. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  38892. }
  38893. else {
  38894. this._position = null;
  38895. }
  38896. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  38897. this.scale = (settings.scale == null) ? 1 : settings.scale;
  38898. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  38899. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  38900. // Layout Engine
  38901. if (settings.layoutEngine != null) {
  38902. if (typeof settings.layoutEngine === "string") {
  38903. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  38904. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  38905. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  38906. }
  38907. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  38908. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  38909. }
  38910. else if (name_1.indexOf("verticalstackpanel") === 0) {
  38911. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  38912. }
  38913. }
  38914. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  38915. this.layoutEngine = settings.layoutEngine;
  38916. }
  38917. }
  38918. // Set the layout/margin stuffs
  38919. if (settings.marginTop) {
  38920. this.margin.setTop(settings.marginTop);
  38921. }
  38922. if (settings.marginLeft) {
  38923. this.margin.setLeft(settings.marginLeft);
  38924. }
  38925. if (settings.marginRight) {
  38926. this.margin.setRight(settings.marginRight);
  38927. }
  38928. if (settings.marginBottom) {
  38929. this.margin.setBottom(settings.marginBottom);
  38930. }
  38931. if (settings.margin) {
  38932. if (typeof settings.margin === "string") {
  38933. this.margin.fromString(settings.margin);
  38934. }
  38935. else {
  38936. this.margin.fromUniformPixels(settings.margin);
  38937. }
  38938. }
  38939. if (settings.marginHAlignment) {
  38940. this.marginAlignment.horizontal = settings.marginHAlignment;
  38941. }
  38942. if (settings.marginVAlignment) {
  38943. this.marginAlignment.vertical = settings.marginVAlignment;
  38944. }
  38945. if (settings.marginAlignment) {
  38946. this.marginAlignment.fromString(settings.marginAlignment);
  38947. }
  38948. if (settings.paddingTop) {
  38949. this.padding.setTop(settings.paddingTop);
  38950. }
  38951. if (settings.paddingLeft) {
  38952. this.padding.setLeft(settings.paddingLeft);
  38953. }
  38954. if (settings.paddingRight) {
  38955. this.padding.setRight(settings.paddingRight);
  38956. }
  38957. if (settings.paddingBottom) {
  38958. this.padding.setBottom(settings.paddingBottom);
  38959. }
  38960. if (settings.padding) {
  38961. this.padding.fromString(settings.padding);
  38962. }
  38963. // Dirty layout and positioning
  38964. this._parentLayoutDirty();
  38965. this._positioningDirty();
  38966. }
  38967. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  38968. get: function () {
  38969. if (!this._actionManager) {
  38970. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  38971. }
  38972. return this._actionManager;
  38973. },
  38974. enumerable: true,
  38975. configurable: true
  38976. });
  38977. /**
  38978. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  38979. * @param predicate the predicate to test on each parent
  38980. * @return the first primitive where the predicate was successful
  38981. */
  38982. Prim2DBase.prototype.traverseUp = function (predicate) {
  38983. var p = this;
  38984. while (p != null) {
  38985. if (predicate(p)) {
  38986. return p;
  38987. }
  38988. p = p._parent;
  38989. }
  38990. return null;
  38991. };
  38992. Object.defineProperty(Prim2DBase.prototype, "owner", {
  38993. /**
  38994. * Retrieve the owner Canvas2D
  38995. */
  38996. get: function () {
  38997. return this._owner;
  38998. },
  38999. enumerable: true,
  39000. configurable: true
  39001. });
  39002. Object.defineProperty(Prim2DBase.prototype, "parent", {
  39003. /**
  39004. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  39005. */
  39006. get: function () {
  39007. return this._parent;
  39008. },
  39009. enumerable: true,
  39010. configurable: true
  39011. });
  39012. Object.defineProperty(Prim2DBase.prototype, "children", {
  39013. /**
  39014. * The array of direct children primitives
  39015. */
  39016. get: function () {
  39017. return this._children;
  39018. },
  39019. enumerable: true,
  39020. configurable: true
  39021. });
  39022. Object.defineProperty(Prim2DBase.prototype, "id", {
  39023. /**
  39024. * The identifier of this primitive, may not be unique, it's for information purpose only
  39025. */
  39026. get: function () {
  39027. return this._id;
  39028. },
  39029. enumerable: true,
  39030. configurable: true
  39031. });
  39032. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  39033. get: function () {
  39034. if (this._actualPosition != null) {
  39035. return this._actualPosition;
  39036. }
  39037. if (this._position != null) {
  39038. return this._position;
  39039. }
  39040. // At least return 0,0, we can't return null on actualPosition
  39041. return Prim2DBase._nullPosition;
  39042. },
  39043. /**
  39044. * DO NOT INVOKE for internal purpose only
  39045. */
  39046. set: function (val) {
  39047. this._actualPosition = val;
  39048. },
  39049. enumerable: true,
  39050. configurable: true
  39051. });
  39052. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  39053. /**
  39054. * Shortcut to actualPosition.x
  39055. */
  39056. get: function () {
  39057. return this.actualPosition.x;
  39058. },
  39059. enumerable: true,
  39060. configurable: true
  39061. });
  39062. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  39063. /**
  39064. * Shortcut to actualPosition.y
  39065. */
  39066. get: function () {
  39067. return this.actualPosition.y;
  39068. },
  39069. enumerable: true,
  39070. configurable: true
  39071. });
  39072. Object.defineProperty(Prim2DBase.prototype, "position", {
  39073. /**
  39074. * Position of the primitive, relative to its parent.
  39075. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  39076. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  39077. * Setting this property may have no effect is specific alignment are in effect.
  39078. */
  39079. get: function () {
  39080. return this._position || Prim2DBase._nullPosition;
  39081. },
  39082. set: function (value) {
  39083. if (!this._checkPositionChange()) {
  39084. return;
  39085. }
  39086. this._position = value;
  39087. this.markAsDirty("actualPosition");
  39088. },
  39089. enumerable: true,
  39090. configurable: true
  39091. });
  39092. Object.defineProperty(Prim2DBase.prototype, "x", {
  39093. /**
  39094. * Direct access to the position.x value of the primitive
  39095. * Use this property when you only want to change one component of the position property
  39096. */
  39097. get: function () {
  39098. if (!this._position) {
  39099. return null;
  39100. }
  39101. return this._position.x;
  39102. },
  39103. set: function (value) {
  39104. if (!this._checkPositionChange()) {
  39105. return;
  39106. }
  39107. if (!this._position) {
  39108. this._position = BABYLON.Vector2.Zero();
  39109. }
  39110. if (this._position.x === value) {
  39111. return;
  39112. }
  39113. this._position.x = value;
  39114. this.markAsDirty("position");
  39115. this.markAsDirty("actualPosition");
  39116. },
  39117. enumerable: true,
  39118. configurable: true
  39119. });
  39120. Object.defineProperty(Prim2DBase.prototype, "y", {
  39121. /**
  39122. * Direct access to the position.y value of the primitive
  39123. * Use this property when you only want to change one component of the position property
  39124. */
  39125. get: function () {
  39126. if (!this._position) {
  39127. return null;
  39128. }
  39129. return this._position.y;
  39130. },
  39131. set: function (value) {
  39132. if (!this._checkPositionChange()) {
  39133. return;
  39134. }
  39135. if (!this._position) {
  39136. this._position = BABYLON.Vector2.Zero();
  39137. }
  39138. if (this._position.y === value) {
  39139. return;
  39140. }
  39141. this._position.y = value;
  39142. this.markAsDirty("position");
  39143. this.markAsDirty("actualPosition");
  39144. },
  39145. enumerable: true,
  39146. configurable: true
  39147. });
  39148. Object.defineProperty(Prim2DBase.prototype, "size", {
  39149. /**
  39150. * Size of the primitive or its bounding area
  39151. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  39152. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  39153. */
  39154. get: function () {
  39155. if (!this._size || this._size.width == null || this._size.height == null) {
  39156. if (Prim2DBase.boundinbBoxReentrency) {
  39157. return Prim2DBase.nullSize;
  39158. }
  39159. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39160. return this._boundingSize;
  39161. }
  39162. Prim2DBase.boundinbBoxReentrency = true;
  39163. var b = this.boundingInfo;
  39164. Prim2DBase.boundinbBoxReentrency = false;
  39165. return this._boundingSize;
  39166. }
  39167. return this._size;
  39168. },
  39169. set: function (value) {
  39170. this._size = value;
  39171. },
  39172. enumerable: true,
  39173. configurable: true
  39174. });
  39175. Object.defineProperty(Prim2DBase.prototype, "width", {
  39176. /**
  39177. * Direct access to the size.width value of the primitive
  39178. * Use this property when you only want to change one component of the size property
  39179. */
  39180. get: function () {
  39181. if (!this.size) {
  39182. return null;
  39183. }
  39184. return this.size.width;
  39185. },
  39186. set: function (value) {
  39187. if (!this.size) {
  39188. this.size = new BABYLON.Size(value, 0);
  39189. return;
  39190. }
  39191. if (this.size.width === value) {
  39192. return;
  39193. }
  39194. this.size.width = value;
  39195. this.markAsDirty("size");
  39196. this._positioningDirty();
  39197. },
  39198. enumerable: true,
  39199. configurable: true
  39200. });
  39201. Object.defineProperty(Prim2DBase.prototype, "height", {
  39202. /**
  39203. * Direct access to the size.height value of the primitive
  39204. * Use this property when you only want to change one component of the size property
  39205. */
  39206. get: function () {
  39207. if (!this.size) {
  39208. return null;
  39209. }
  39210. return this.size.height;
  39211. },
  39212. set: function (value) {
  39213. if (!this.size) {
  39214. this.size = new BABYLON.Size(0, value);
  39215. return;
  39216. }
  39217. if (this.size.height === value) {
  39218. return;
  39219. }
  39220. this.size.height = value;
  39221. this.markAsDirty("size");
  39222. this._positioningDirty();
  39223. },
  39224. enumerable: true,
  39225. configurable: true
  39226. });
  39227. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  39228. get: function () {
  39229. return this._rotation;
  39230. },
  39231. set: function (value) {
  39232. this._rotation = value;
  39233. },
  39234. enumerable: true,
  39235. configurable: true
  39236. });
  39237. Object.defineProperty(Prim2DBase.prototype, "scale", {
  39238. get: function () {
  39239. return this._scale;
  39240. },
  39241. set: function (value) {
  39242. this._scale = value;
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  39248. /**
  39249. * Return the size of the primitive as it's being rendered into the target.
  39250. * 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.
  39251. * BEWARE: don't use the setter, it's for internal purpose only
  39252. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  39253. */
  39254. get: function () {
  39255. if (this._actualSize) {
  39256. return this._actualSize;
  39257. }
  39258. return this._size;
  39259. },
  39260. set: function (value) {
  39261. if (this._actualSize.equals(value)) {
  39262. return;
  39263. }
  39264. this._actualSize = value;
  39265. },
  39266. enumerable: true,
  39267. configurable: true
  39268. });
  39269. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  39270. get: function () {
  39271. if (this._manualZOrder != null) {
  39272. return this._manualZOrder;
  39273. }
  39274. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39275. this._updateZOrder();
  39276. }
  39277. return (1 - this._zOrder);
  39278. },
  39279. enumerable: true,
  39280. configurable: true
  39281. });
  39282. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  39283. /**
  39284. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  39285. * The Primitive's size won't be less than specified.
  39286. * The default value depends of the Primitive type
  39287. */
  39288. get: function () {
  39289. return this._minSize;
  39290. },
  39291. set: function (value) {
  39292. if (this._minSize && value && this._minSize.equals(value)) {
  39293. return;
  39294. }
  39295. this._minSize = value;
  39296. this._parentLayoutDirty();
  39297. },
  39298. enumerable: true,
  39299. configurable: true
  39300. });
  39301. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  39302. /**
  39303. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  39304. * The Primitive's size won't be more than specified.
  39305. * The default value depends of the Primitive type
  39306. */
  39307. get: function () {
  39308. return this._maxSize;
  39309. },
  39310. set: function (value) {
  39311. if (this._maxSize && value && this._maxSize.equals(value)) {
  39312. return;
  39313. }
  39314. this._maxSize = value;
  39315. this._parentLayoutDirty();
  39316. },
  39317. enumerable: true,
  39318. configurable: true
  39319. });
  39320. Object.defineProperty(Prim2DBase.prototype, "origin", {
  39321. /**
  39322. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  39323. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  39324. * For instance:
  39325. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  39326. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  39327. * 0,1 means the center is top/left
  39328. * @returns The normalized center.
  39329. */
  39330. get: function () {
  39331. return this._origin;
  39332. },
  39333. set: function (value) {
  39334. this._origin = value;
  39335. },
  39336. enumerable: true,
  39337. configurable: true
  39338. });
  39339. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  39340. get: function () {
  39341. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  39342. },
  39343. set: function (value) {
  39344. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  39345. },
  39346. enumerable: true,
  39347. configurable: true
  39348. });
  39349. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  39350. get: function () {
  39351. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  39352. },
  39353. set: function (value) {
  39354. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  39355. },
  39356. enumerable: true,
  39357. configurable: true
  39358. });
  39359. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  39360. get: function () {
  39361. return this._manualZOrder;
  39362. },
  39363. set: function (value) {
  39364. if (this._manualZOrder === value) {
  39365. return;
  39366. }
  39367. this._manualZOrder = value;
  39368. this.onZOrderChanged();
  39369. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  39370. this._actualZOrderChangedObservable.notifyObservers(value);
  39371. }
  39372. },
  39373. enumerable: true,
  39374. configurable: true
  39375. });
  39376. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  39377. get: function () {
  39378. return this._manualZOrder != null;
  39379. },
  39380. enumerable: true,
  39381. configurable: true
  39382. });
  39383. Object.defineProperty(Prim2DBase.prototype, "margin", {
  39384. get: function () {
  39385. var _this = this;
  39386. if (!this._margin) {
  39387. this._margin = new PrimitiveThickness(function () {
  39388. if (!_this.parent) {
  39389. return null;
  39390. }
  39391. return _this.parent.margin;
  39392. }, function () { return _this._positioningDirty(); });
  39393. }
  39394. return this._margin;
  39395. },
  39396. enumerable: true,
  39397. configurable: true
  39398. });
  39399. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  39400. get: function () {
  39401. return (this._margin !== null) || (this._marginAlignment !== null);
  39402. },
  39403. enumerable: true,
  39404. configurable: true
  39405. });
  39406. Object.defineProperty(Prim2DBase.prototype, "padding", {
  39407. get: function () {
  39408. var _this = this;
  39409. if (!this._padding) {
  39410. this._padding = new PrimitiveThickness(function () {
  39411. if (!_this.parent) {
  39412. return null;
  39413. }
  39414. return _this.parent.padding;
  39415. }, function () { return _this._positioningDirty(); });
  39416. }
  39417. return this._padding;
  39418. },
  39419. enumerable: true,
  39420. configurable: true
  39421. });
  39422. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  39423. get: function () {
  39424. return this._padding !== null;
  39425. },
  39426. enumerable: true,
  39427. configurable: true
  39428. });
  39429. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  39430. get: function () {
  39431. var _this = this;
  39432. if (!this._marginAlignment) {
  39433. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  39434. }
  39435. return this._marginAlignment;
  39436. },
  39437. enumerable: true,
  39438. configurable: true
  39439. });
  39440. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  39441. get: function () {
  39442. return this._opacity;
  39443. },
  39444. set: function (value) {
  39445. if (value < 0) {
  39446. value = 0;
  39447. }
  39448. else if (value > 1) {
  39449. value = 1;
  39450. }
  39451. if (this._opacity === value) {
  39452. return;
  39453. }
  39454. this._opacity = value;
  39455. this._updateRenderMode();
  39456. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39457. this._spreadActualOpacityChanged();
  39458. },
  39459. enumerable: true,
  39460. configurable: true
  39461. });
  39462. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  39463. get: function () {
  39464. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  39465. var cur = this.parent;
  39466. var op = this.opacity;
  39467. while (cur) {
  39468. op *= cur.opacity;
  39469. cur = cur.parent;
  39470. }
  39471. this._actualOpacity = op;
  39472. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39473. }
  39474. return this._actualOpacity;
  39475. },
  39476. enumerable: true,
  39477. configurable: true
  39478. });
  39479. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  39480. /**
  39481. * Get/set the layout engine to use for this primitive.
  39482. * The default layout engine is the CanvasLayoutEngine.
  39483. */
  39484. get: function () {
  39485. if (!this._layoutEngine) {
  39486. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  39487. }
  39488. return this._layoutEngine;
  39489. },
  39490. set: function (value) {
  39491. if (this._layoutEngine === value) {
  39492. return;
  39493. }
  39494. this._changeLayoutEngine(value);
  39495. },
  39496. enumerable: true,
  39497. configurable: true
  39498. });
  39499. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  39500. /**
  39501. * Get/set the layout are of this primitive.
  39502. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  39503. * The setter should only be called by a Layout Engine class.
  39504. */
  39505. get: function () {
  39506. return this._layoutArea;
  39507. },
  39508. set: function (val) {
  39509. if (this._layoutArea.equals(val)) {
  39510. return;
  39511. }
  39512. this._positioningDirty();
  39513. this._layoutArea = val;
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  39519. /**
  39520. * Get/set the layout area position (relative to the parent primitive).
  39521. * The setter should only be called by a Layout Engine class.
  39522. */
  39523. get: function () {
  39524. return this._layoutAreaPos;
  39525. },
  39526. set: function (val) {
  39527. if (this._layoutAreaPos.equals(val)) {
  39528. return;
  39529. }
  39530. this._positioningDirty();
  39531. this._layoutAreaPos = val;
  39532. },
  39533. enumerable: true,
  39534. configurable: true
  39535. });
  39536. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  39537. /**
  39538. * Define if the Primitive can be subject to intersection test or not (default is true)
  39539. */
  39540. get: function () {
  39541. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  39542. },
  39543. set: function (value) {
  39544. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  39545. },
  39546. enumerable: true,
  39547. configurable: true
  39548. });
  39549. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  39550. /**
  39551. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  39552. */
  39553. get: function () {
  39554. return this._hierarchyDepth;
  39555. },
  39556. enumerable: true,
  39557. configurable: true
  39558. });
  39559. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  39560. /**
  39561. * Retrieve the Group that is responsible to render this primitive
  39562. */
  39563. get: function () {
  39564. return this._renderGroup;
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  39570. /**
  39571. * Get the global transformation matrix of the primitive
  39572. */
  39573. get: function () {
  39574. return this._globalTransform;
  39575. },
  39576. enumerable: true,
  39577. configurable: true
  39578. });
  39579. /**
  39580. * return the global position of the primitive, relative to its canvas
  39581. */
  39582. Prim2DBase.prototype.getGlobalPosition = function () {
  39583. var v = new BABYLON.Vector2(0, 0);
  39584. this.getGlobalPositionByRef(v);
  39585. return v;
  39586. };
  39587. /**
  39588. * return the global position of the primitive, relative to its canvas
  39589. * @param v the valid Vector2 object where the global position will be stored
  39590. */
  39591. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  39592. v.x = this.globalTransform.m[12];
  39593. v.y = this.globalTransform.m[13];
  39594. };
  39595. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  39596. /**
  39597. * Get invert of the global transformation matrix of the primitive
  39598. */
  39599. get: function () {
  39600. return this._invGlobalTransform;
  39601. },
  39602. enumerable: true,
  39603. configurable: true
  39604. });
  39605. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  39606. /**
  39607. * Get the local transformation of the primitive
  39608. */
  39609. get: function () {
  39610. this._updateLocalTransform();
  39611. return this._localTransform;
  39612. },
  39613. enumerable: true,
  39614. configurable: true
  39615. });
  39616. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  39617. /**
  39618. * Get the boundingInfo associated to the primitive and its children.
  39619. * The value is supposed to be always up to date
  39620. */
  39621. get: function () {
  39622. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  39623. if (this.owner) {
  39624. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  39625. }
  39626. if (this.isSizedByContent) {
  39627. this._boundingInfo.clear();
  39628. }
  39629. else {
  39630. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  39631. }
  39632. var bi = this._boundingInfo;
  39633. var tps = new BABYLON.BoundingInfo2D();
  39634. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39635. var curChild = _a[_i];
  39636. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  39637. bi.unionToRef(tps, bi);
  39638. }
  39639. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  39640. 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);
  39641. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  39642. }
  39643. return this._boundingInfo;
  39644. },
  39645. enumerable: true,
  39646. configurable: true
  39647. });
  39648. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  39649. /**
  39650. * Determine if the size is automatically computed or fixed because manually specified.
  39651. * Use the actualSize property to get the final/real size of the primitive
  39652. * @returns true if the size is automatically computed, false if it were manually specified.
  39653. */
  39654. get: function () {
  39655. return this._size == null;
  39656. },
  39657. enumerable: true,
  39658. configurable: true
  39659. });
  39660. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  39661. /**
  39662. * Return true if this prim has an auto size which is set by the children's global bounding box
  39663. */
  39664. get: function () {
  39665. return (this._size == null) && (this._children.length > 0);
  39666. },
  39667. enumerable: true,
  39668. configurable: true
  39669. });
  39670. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  39671. /**
  39672. * Determine if the position is automatically computed or fixed because manually specified.
  39673. * Use the actualPosition property to get the final/real position of the primitive
  39674. * @returns true if the position is automatically computed, false if it were manually specified.
  39675. */
  39676. get: function () {
  39677. return this._position == null;
  39678. },
  39679. enumerable: true,
  39680. configurable: true
  39681. });
  39682. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  39683. /**
  39684. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  39685. */
  39686. get: function () {
  39687. return this._pointerEventObservable;
  39688. },
  39689. enumerable: true,
  39690. configurable: true
  39691. });
  39692. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  39693. get: function () {
  39694. if (!this._actualZOrderChangedObservable) {
  39695. this._actualZOrderChangedObservable = new BABYLON.Observable();
  39696. }
  39697. return this._actualZOrderChangedObservable;
  39698. },
  39699. enumerable: true,
  39700. configurable: true
  39701. });
  39702. Prim2DBase.prototype.findById = function (id) {
  39703. if (this._id === id) {
  39704. return this;
  39705. }
  39706. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39707. var child = _a[_i];
  39708. var r = child.findById(id);
  39709. if (r != null) {
  39710. return r;
  39711. }
  39712. }
  39713. };
  39714. Prim2DBase.prototype.onZOrderChanged = function () {
  39715. };
  39716. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  39717. return false;
  39718. };
  39719. /**
  39720. * Capture all the Events of the given PointerId for this primitive.
  39721. * Don't forget to call releasePointerEventsCapture when done.
  39722. * @param pointerId the Id of the pointer to capture the events from.
  39723. */
  39724. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  39725. return this.owner._setPointerCapture(pointerId, this);
  39726. };
  39727. /**
  39728. * Release a captured pointer made with setPointerEventCapture.
  39729. * @param pointerId the Id of the pointer to release the capture from.
  39730. */
  39731. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  39732. return this.owner._releasePointerCapture(pointerId, this);
  39733. };
  39734. /**
  39735. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  39736. * @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.
  39737. */
  39738. Prim2DBase.prototype.intersect = function (intersectInfo) {
  39739. if (!intersectInfo) {
  39740. return false;
  39741. }
  39742. // If this is null it means this method is call for the first level, initialize stuffs
  39743. var firstLevel = !intersectInfo._globalPickPosition;
  39744. if (firstLevel) {
  39745. // 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).
  39746. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  39747. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  39748. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  39749. intersectInfo.intersectedPrimitives = new Array();
  39750. intersectInfo.topMostIntersectedPrimitive = null;
  39751. }
  39752. if (!intersectInfo.intersectHidden && !this.isVisible) {
  39753. return false;
  39754. }
  39755. // Fast rejection test with boundingInfo
  39756. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  39757. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  39758. intersectInfo._exit(firstLevel);
  39759. return false;
  39760. }
  39761. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  39762. var levelIntersectRes = false;
  39763. if (this.isPickable) {
  39764. levelIntersectRes = this.levelIntersect(intersectInfo);
  39765. if (levelIntersectRes) {
  39766. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  39767. intersectInfo.intersectedPrimitives.push(pii);
  39768. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  39769. intersectInfo.topMostIntersectedPrimitive = pii;
  39770. }
  39771. // If we must stop at the first intersection, we're done, quit!
  39772. if (intersectInfo.findFirstOnly) {
  39773. intersectInfo._exit(firstLevel);
  39774. return true;
  39775. }
  39776. }
  39777. }
  39778. // Recurse to children if needed
  39779. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  39780. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39781. var curChild = _a[_i];
  39782. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  39783. if (!curChild.isPickable || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  39784. continue;
  39785. }
  39786. // Must compute the localPickLocation for the children level
  39787. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  39788. // If we got an intersection with the child and we only need to find the first one, quit!
  39789. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  39790. intersectInfo._exit(firstLevel);
  39791. return true;
  39792. }
  39793. }
  39794. }
  39795. intersectInfo._exit(firstLevel);
  39796. return intersectInfo.isIntersected;
  39797. };
  39798. Prim2DBase.prototype.moveChild = function (child, previous) {
  39799. if (child.parent !== this) {
  39800. return false;
  39801. }
  39802. var childIndex = this._children.indexOf(child);
  39803. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  39804. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  39805. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39806. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  39807. }
  39808. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  39809. };
  39810. Prim2DBase.prototype.addChild = function (child) {
  39811. child._parent = this;
  39812. this._boundingBoxDirty();
  39813. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39814. if (flat) {
  39815. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  39816. child._setZOrder(this._zOrder, true);
  39817. child._zMax = this._zOrder;
  39818. }
  39819. else {
  39820. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  39821. }
  39822. var length = this._children.push(child);
  39823. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  39824. };
  39825. /**
  39826. * Dispose the primitive, remove it from its parent.
  39827. */
  39828. Prim2DBase.prototype.dispose = function () {
  39829. if (!_super.prototype.dispose.call(this)) {
  39830. return false;
  39831. }
  39832. if (this._actionManager) {
  39833. this._actionManager.dispose();
  39834. this._actionManager = null;
  39835. }
  39836. // If there's a parent, remove this object from its parent list
  39837. if (this._parent) {
  39838. var i = this._parent._children.indexOf(this);
  39839. if (i !== undefined) {
  39840. this._parent._children.splice(i, 1);
  39841. }
  39842. this._parent = null;
  39843. }
  39844. // Recurse dispose to children
  39845. if (this._children) {
  39846. while (this._children.length > 0) {
  39847. this._children[this._children.length - 1].dispose();
  39848. }
  39849. }
  39850. return true;
  39851. };
  39852. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  39853. if (this._renderGroup) {
  39854. this._renderGroup._addPrimToDirtyList(this);
  39855. }
  39856. };
  39857. Prim2DBase.prototype._needPrepare = function () {
  39858. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  39859. };
  39860. Prim2DBase.prototype._prepareRender = function (context) {
  39861. this._prepareRenderPre(context);
  39862. this._prepareRenderPost(context);
  39863. };
  39864. Prim2DBase.prototype._prepareRenderPre = function (context) {
  39865. };
  39866. Prim2DBase.prototype._prepareRenderPost = function (context) {
  39867. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  39868. if (this instanceof BABYLON.Group2D) {
  39869. var self = this;
  39870. if (self.isRenderableGroup) {
  39871. return;
  39872. }
  39873. }
  39874. // Check if we need to recurse the prepare to children primitives
  39875. // - must have children
  39876. // - the global transform of this level have changed, or
  39877. // - the visible state of primitive has changed
  39878. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  39879. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  39880. this._children.forEach(function (c) {
  39881. // As usual stop the recursion if we meet a renderable group
  39882. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  39883. c._prepareRender(context);
  39884. }
  39885. });
  39886. }
  39887. // Finally reset the dirty flags as we've processed everything
  39888. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  39889. this._instanceDirtyFlags = 0;
  39890. };
  39891. Prim2DBase.prototype._canvasPreInit = function (settings) {
  39892. };
  39893. Prim2DBase.CheckParent = function (parent) {
  39894. //if (!Prim2DBase._isCanvasInit && !parent) {
  39895. // 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)");
  39896. //}
  39897. };
  39898. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  39899. for (var _i = 0; _i < list.length; _i++) {
  39900. var cur = list[_i];
  39901. cur.updateCachedStates(recurse);
  39902. }
  39903. };
  39904. Prim2DBase.prototype._parentLayoutDirty = function () {
  39905. if (!this._parent || this._parent.isDisposed) {
  39906. return;
  39907. }
  39908. this._parent._setLayoutDirty();
  39909. };
  39910. Prim2DBase.prototype._setLayoutDirty = function () {
  39911. if (!this.isDirty) {
  39912. this.onPrimBecomesDirty();
  39913. }
  39914. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  39915. };
  39916. Prim2DBase.prototype._checkPositionChange = function () {
  39917. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  39918. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  39919. return false;
  39920. }
  39921. return true;
  39922. };
  39923. Prim2DBase.prototype._positioningDirty = function () {
  39924. if (!this.isDirty) {
  39925. this.onPrimBecomesDirty();
  39926. }
  39927. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  39928. };
  39929. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  39930. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  39931. var child = _a[_i];
  39932. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  39933. child._spreadActualOpacityChanged();
  39934. }
  39935. };
  39936. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  39937. this._layoutEngine = engine;
  39938. };
  39939. Prim2DBase.prototype._updateLocalTransform = function () {
  39940. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.originProperty.flagId;
  39941. if (this.checkPropertiesDirty(tflags)) {
  39942. if (this.owner) {
  39943. this.owner.addupdateLocalTransformCounter(1);
  39944. }
  39945. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  39946. var local;
  39947. var pos = this.position;
  39948. if (this._origin.x === 0 && this._origin.y === 0) {
  39949. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale, this._scale, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  39950. this._localTransform = local;
  39951. }
  39952. else {
  39953. // -Origin offset
  39954. var as = this.actualSize;
  39955. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  39956. // -Origin * rotation
  39957. rot.toRotationMatrix(Prim2DBase._t1);
  39958. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  39959. // -Origin * rotation * scale
  39960. BABYLON.Matrix.ScalingToRef(this._scale, this._scale, 1, Prim2DBase._t0);
  39961. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  39962. // -Origin * rotation * scale * (Origin + Position)
  39963. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  39964. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  39965. }
  39966. this.clearPropertiesDirty(tflags);
  39967. return true;
  39968. }
  39969. return false;
  39970. };
  39971. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  39972. if (this.isDisposed) {
  39973. return;
  39974. }
  39975. this.owner.addCachedGroupRenderCounter(1);
  39976. // Check if the parent is synced
  39977. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  39978. this._parent.updateCachedStates(false);
  39979. }
  39980. // Update Z-Order if needed
  39981. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  39982. this._updateZOrder();
  39983. }
  39984. // Update actualSize only if there' not positioning to recompute and the size changed
  39985. // Otherwise positioning will take care of it.
  39986. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39987. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  39988. var size = this.size;
  39989. if (size) {
  39990. if (this.size.width != null) {
  39991. this.actualSize.width = this.size.width;
  39992. }
  39993. if (this.size.height != null) {
  39994. this.actualSize.height = this.size.height;
  39995. }
  39996. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  39997. }
  39998. }
  39999. // Check for layout update
  40000. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40001. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  40002. this.owner.addUpdateLayoutCounter(1);
  40003. this._layoutEngine.updateLayout(this);
  40004. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  40005. }
  40006. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40007. var autoContentChanged = false;
  40008. if (this.isSizeAuto) {
  40009. if (!this._lastAutoSizeArea) {
  40010. autoContentChanged = this.size !== null;
  40011. }
  40012. else {
  40013. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  40014. }
  40015. }
  40016. // Check for positioning update
  40017. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  40018. this._updatePositioning();
  40019. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40020. if (sizeDirty) {
  40021. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  40022. }
  40023. positioningComputed = true;
  40024. }
  40025. if (positioningComputed && this._parent) {
  40026. this._parentContentArea.copyFrom(this._parent.contentArea);
  40027. }
  40028. // Check if we must update this prim
  40029. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  40030. this.owner.addUpdateGlobalTransformCounter(1);
  40031. var curVisibleState = this.isVisible;
  40032. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  40033. // Detect a change of visibility
  40034. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  40035. // Get/compute the localTransform
  40036. var localDirty = this._updateLocalTransform();
  40037. var parentPaddingChanged = false;
  40038. var parentPaddingOffset = Prim2DBase._v0;
  40039. if (this._parent) {
  40040. parentPaddingOffset = this._parent._paddingOffset;
  40041. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  40042. }
  40043. // Check if there are changes in the parent that will force us to update the global matrix
  40044. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  40045. // Check if we have to update the globalTransform
  40046. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  40047. var globalTransform = this._parent ? this._parent._globalTransform : null;
  40048. var localTransform;
  40049. Prim2DBase._transMtx.copyFrom(this._localTransform);
  40050. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  40051. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  40052. localTransform = Prim2DBase._transMtx;
  40053. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  40054. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  40055. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  40056. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  40057. }
  40058. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  40059. }
  40060. if (recurse) {
  40061. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40062. var child = _a[_i];
  40063. // Stop the recursion if we meet a renderable group
  40064. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  40065. }
  40066. }
  40067. };
  40068. Prim2DBase.prototype._updatePositioning = function () {
  40069. if (this.owner) {
  40070. this.owner.addUpdatePositioningCounter(1);
  40071. }
  40072. // From this point we assume that the primitive layoutArea is computed and up to date.
  40073. // We know have to :
  40074. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  40075. // 2. Determine the contentArea based on the padding property.
  40076. // 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
  40077. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  40078. if (this.actualSize.width == null) {
  40079. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  40080. }
  40081. if (this.actualSize.height == null) {
  40082. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  40083. }
  40084. }
  40085. // Apply margin
  40086. if (this._hasMargin) {
  40087. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40088. this.actualSize = Prim2DBase._size.clone();
  40089. }
  40090. var isSizeAuto = this.isSizeAuto;
  40091. if (this._hasPadding) {
  40092. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  40093. if (isSizeAuto) {
  40094. var content = this.size.clone();
  40095. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  40096. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40097. this._contentArea.copyFrom(content);
  40098. this.actualSize = Prim2DBase._size.clone();
  40099. // Changing the padding has resize the prim, which forces us to recompute margin again
  40100. if (this._hasMargin) {
  40101. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  40102. }
  40103. }
  40104. else {
  40105. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40106. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40107. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40108. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  40109. this._paddingOffset.x += Prim2DBase._icPos.x;
  40110. this._paddingOffset.y += Prim2DBase._icPos.y;
  40111. this._contentArea.copyFrom(Prim2DBase._size);
  40112. }
  40113. }
  40114. else {
  40115. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  40116. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  40117. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  40118. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  40119. this._contentArea.copyFrom(Prim2DBase._icArea);
  40120. }
  40121. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  40122. this.actualPosition = aPos;
  40123. if (isSizeAuto) {
  40124. this._lastAutoSizeArea = this.size;
  40125. }
  40126. };
  40127. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  40128. /**
  40129. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  40130. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  40131. */
  40132. get: function () {
  40133. // Check for positioning update
  40134. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  40135. this._updatePositioning();
  40136. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  40137. }
  40138. return this._contentArea;
  40139. },
  40140. enumerable: true,
  40141. configurable: true
  40142. });
  40143. Prim2DBase.prototype._patchHierarchy = function (owner) {
  40144. this._owner = owner;
  40145. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  40146. if (this._renderGroup != null) {
  40147. return;
  40148. }
  40149. if (this instanceof BABYLON.Group2D) {
  40150. var group = this;
  40151. group.detectGroupStates();
  40152. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  40153. group.owner._registerTrackedNode(this);
  40154. }
  40155. }
  40156. if (this._parent) {
  40157. this._renderGroup = this.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  40158. this._parentLayoutDirty();
  40159. }
  40160. // Make sure the prim is in the dirtyList if it should be
  40161. if (this._renderGroup && this.isDirty) {
  40162. var list = this._renderGroup._renderableData._primDirtyList;
  40163. var i = list.indexOf(this);
  40164. if (i === -1) {
  40165. list.push(this);
  40166. }
  40167. }
  40168. // Recurse
  40169. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40170. var child = _a[_i];
  40171. child._hierarchyDepth = this._hierarchyDepth + 1;
  40172. child._patchHierarchy(owner);
  40173. }
  40174. };
  40175. Prim2DBase.prototype._updateZOrder = function () {
  40176. var prevLinPos = this._primLinearPosition;
  40177. var startI = 0;
  40178. var startZ = this._zOrder;
  40179. // 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
  40180. var childrenCount = this._children.length;
  40181. if (this._firstZDirtyIndex > 0) {
  40182. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  40183. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  40184. prevLinPos = prevPrim._primLinearPosition;
  40185. startI = this._firstZDirtyIndex - 1;
  40186. startZ = prevPrim._zOrder;
  40187. }
  40188. }
  40189. var startPos = prevLinPos;
  40190. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  40191. Prim2DBase._totalCount = 0;
  40192. for (var i = startI; i < childrenCount; i++) {
  40193. var child = this._children[i];
  40194. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40195. }
  40196. // Compute the new Z-Order for all the primitives
  40197. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  40198. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  40199. // 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.
  40200. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  40201. // 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...
  40202. if (Prim2DBase._zRebuildReentrency) {
  40203. var p = this._parent;
  40204. if (p == null) {
  40205. // 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...)
  40206. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  40207. Prim2DBase._zRebuildReentrency = false;
  40208. return;
  40209. }
  40210. p._firstZDirtyIndex = 0;
  40211. return p._updateZOrder();
  40212. }
  40213. Prim2DBase._zRebuildReentrency = true;
  40214. this._firstZDirtyIndex = 0;
  40215. this._updateZOrder();
  40216. Prim2DBase._zRebuildReentrency = false;
  40217. }
  40218. for (var i = startI; i < childrenCount; i++) {
  40219. var child = this._children[i];
  40220. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  40221. }
  40222. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  40223. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  40224. var p = _a[_i];
  40225. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  40226. }
  40227. Prim2DBase._zOrderChangedNotifList.splice(0);
  40228. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40229. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40230. };
  40231. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  40232. if (this.isManualZOrder) {
  40233. return prevLinPos;
  40234. }
  40235. this._primLinearPosition = ++prevLinPos;
  40236. Prim2DBase._totalCount++;
  40237. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40238. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  40239. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40240. var child = _a[_i];
  40241. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  40242. }
  40243. }
  40244. return prevLinPos;
  40245. };
  40246. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  40247. if (this.isManualZOrder) {
  40248. return null;
  40249. }
  40250. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  40251. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40252. this._setZOrder(newZ, false);
  40253. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40254. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40255. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40256. }
  40257. var curZ = newZ;
  40258. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  40259. if (isFlat) {
  40260. if (this._children.length > 0) {
  40261. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  40262. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40263. var child = _a[_i];
  40264. child._updatePrimitiveFlatZOrder(this._zOrder);
  40265. }
  40266. }
  40267. }
  40268. else {
  40269. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  40270. var child = _c[_b];
  40271. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  40272. if (r != null) {
  40273. curZ = r;
  40274. }
  40275. }
  40276. }
  40277. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  40278. return curZ;
  40279. };
  40280. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  40281. if (this.isManualZOrder) {
  40282. return;
  40283. }
  40284. this._setZOrder(newZ, false);
  40285. this._zMax = newZ;
  40286. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40287. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40288. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  40289. }
  40290. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  40291. var child = _a[_i];
  40292. child._updatePrimitiveFlatZOrder(newZ);
  40293. }
  40294. };
  40295. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  40296. if (newZ !== this._zOrder) {
  40297. this._zOrder = newZ;
  40298. if (!this.isDirty) {
  40299. this.onPrimBecomesDirty();
  40300. }
  40301. this.onZOrderChanged();
  40302. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40303. if (directEmit) {
  40304. this._actualZOrderChangedObservable.notifyObservers(newZ);
  40305. }
  40306. else {
  40307. Prim2DBase._zOrderChangedNotifList.push(this);
  40308. }
  40309. }
  40310. }
  40311. };
  40312. Prim2DBase.prototype._updateRenderMode = function () {
  40313. };
  40314. /**
  40315. * This method is used to alter the contentArea of the Primitive before margin is applied.
  40316. * 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.
  40317. * @param primSize the current size of the primitive
  40318. * @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!
  40319. * @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!
  40320. */
  40321. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  40322. initialContentArea.copyFrom(primSize);
  40323. initialContentPosition.x = initialContentPosition.y = 0;
  40324. };
  40325. /**
  40326. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  40327. * Check the Rectangle2D implementation for a concrete application.
  40328. * @param primSize the current size of the primitive
  40329. * @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!
  40330. */
  40331. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  40332. newPrimSize.copyFrom(primSize);
  40333. };
  40334. Prim2DBase.PRIM2DBASE_PROPCOUNT = 15;
  40335. Prim2DBase._bigInt = Math.pow(2, 30);
  40336. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  40337. Prim2DBase.boundinbBoxReentrency = false;
  40338. Prim2DBase.nullSize = BABYLON.Size.Zero();
  40339. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  40340. Prim2DBase._isCanvasInit = false;
  40341. Prim2DBase._t0 = new BABYLON.Matrix();
  40342. Prim2DBase._t1 = new BABYLON.Matrix();
  40343. Prim2DBase._t2 = new BABYLON.Matrix();
  40344. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  40345. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  40346. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  40347. Prim2DBase._icArea = BABYLON.Size.Zero();
  40348. Prim2DBase._size = BABYLON.Size.Zero();
  40349. Prim2DBase._zOrderChangedNotifList = new Array();
  40350. Prim2DBase._zRebuildReentrency = false;
  40351. Prim2DBase._totalCount = 0;
  40352. __decorate([
  40353. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  40354. ], Prim2DBase.prototype, "actualPosition", null);
  40355. __decorate([
  40356. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  40357. ], Prim2DBase.prototype, "position", null);
  40358. __decorate([
  40359. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  40360. ], Prim2DBase.prototype, "size", null);
  40361. __decorate([
  40362. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  40363. ], Prim2DBase.prototype, "rotation", null);
  40364. __decorate([
  40365. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  40366. ], Prim2DBase.prototype, "scale", null);
  40367. __decorate([
  40368. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  40369. ], Prim2DBase.prototype, "origin", null);
  40370. __decorate([
  40371. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  40372. ], Prim2DBase.prototype, "levelVisible", null);
  40373. __decorate([
  40374. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  40375. ], Prim2DBase.prototype, "isVisible", null);
  40376. __decorate([
  40377. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  40378. ], Prim2DBase.prototype, "zOrder", null);
  40379. __decorate([
  40380. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  40381. ], Prim2DBase.prototype, "margin", null);
  40382. __decorate([
  40383. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  40384. ], Prim2DBase.prototype, "padding", null);
  40385. __decorate([
  40386. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  40387. ], Prim2DBase.prototype, "marginAlignment", null);
  40388. __decorate([
  40389. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  40390. ], Prim2DBase.prototype, "opacity", null);
  40391. Prim2DBase = __decorate([
  40392. BABYLON.className("Prim2DBase")
  40393. ], Prim2DBase);
  40394. return Prim2DBase;
  40395. })(BABYLON.SmartPropertyPrim);
  40396. BABYLON.Prim2DBase = Prim2DBase;
  40397. })(BABYLON || (BABYLON = {}));
  40398. var BABYLON;
  40399. (function (BABYLON) {
  40400. var GroupInstanceInfo = (function () {
  40401. function GroupInstanceInfo(owner, mrc, partCount) {
  40402. this._partCount = partCount;
  40403. this.owner = owner;
  40404. this.modelRenderCache = mrc;
  40405. this.modelRenderCache.addRef();
  40406. this.partIndexFromId = new BABYLON.StringDictionary();
  40407. this._usedShaderCategories = new Array(partCount);
  40408. this._strides = new Array(partCount);
  40409. this._opaqueData = null;
  40410. this._alphaTestData = null;
  40411. this._transparentData = null;
  40412. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  40413. }
  40414. GroupInstanceInfo.prototype.dispose = function () {
  40415. if (this._isDisposed) {
  40416. return false;
  40417. }
  40418. if (this.modelRenderCache) {
  40419. this.modelRenderCache.dispose();
  40420. }
  40421. var engine = this.owner.owner.engine;
  40422. if (this.opaqueData) {
  40423. this.opaqueData.forEach(function (d) { return d.dispose(engine); });
  40424. this.opaqueData = null;
  40425. }
  40426. this.partIndexFromId = null;
  40427. this._isDisposed = true;
  40428. return true;
  40429. };
  40430. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  40431. get: function () {
  40432. return this._opaqueData != null;
  40433. },
  40434. enumerable: true,
  40435. configurable: true
  40436. });
  40437. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  40438. get: function () {
  40439. return this._alphaTestData != null;
  40440. },
  40441. enumerable: true,
  40442. configurable: true
  40443. });
  40444. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  40445. get: function () {
  40446. return this._transparentData != null;
  40447. },
  40448. enumerable: true,
  40449. configurable: true
  40450. });
  40451. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  40452. get: function () {
  40453. if (!this._opaqueData) {
  40454. this._opaqueData = new Array(this._partCount);
  40455. for (var i = 0; i < this._partCount; i++) {
  40456. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  40457. }
  40458. }
  40459. return this._opaqueData;
  40460. },
  40461. enumerable: true,
  40462. configurable: true
  40463. });
  40464. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  40465. get: function () {
  40466. if (!this._alphaTestData) {
  40467. this._alphaTestData = new Array(this._partCount);
  40468. for (var i = 0; i < this._partCount; i++) {
  40469. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  40470. }
  40471. }
  40472. return this._alphaTestData;
  40473. },
  40474. enumerable: true,
  40475. configurable: true
  40476. });
  40477. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  40478. get: function () {
  40479. if (!this._transparentData) {
  40480. this._transparentData = new Array(this._partCount);
  40481. for (var i = 0; i < this._partCount; i++) {
  40482. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  40483. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  40484. }
  40485. }
  40486. return this._transparentData;
  40487. },
  40488. enumerable: true,
  40489. configurable: true
  40490. });
  40491. GroupInstanceInfo.prototype.sortTransparentData = function () {
  40492. if (!this.transparentOrderDirty) {
  40493. return;
  40494. }
  40495. for (var i = 0; i < this._transparentData.length; i++) {
  40496. var td = this._transparentData[i];
  40497. td._partData.sort();
  40498. }
  40499. this.transparentOrderDirty = false;
  40500. };
  40501. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  40502. get: function () {
  40503. return this._usedShaderCategories;
  40504. },
  40505. enumerable: true,
  40506. configurable: true
  40507. });
  40508. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  40509. get: function () {
  40510. return this._strides;
  40511. },
  40512. enumerable: true,
  40513. configurable: true
  40514. });
  40515. return GroupInstanceInfo;
  40516. })();
  40517. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  40518. var TransparentSegment = (function () {
  40519. function TransparentSegment() {
  40520. this.groupInsanceInfo = null;
  40521. this.startZ = 0;
  40522. this.endZ = 0;
  40523. this.startDataIndex = 0;
  40524. this.endDataIndex = 0;
  40525. this.partBuffers = null;
  40526. }
  40527. TransparentSegment.prototype.dispose = function (engine) {
  40528. if (this.partBuffers) {
  40529. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  40530. this.partBuffers.splice(0);
  40531. this.partBuffers = null;
  40532. }
  40533. };
  40534. return TransparentSegment;
  40535. })();
  40536. BABYLON.TransparentSegment = TransparentSegment;
  40537. var GroupInfoPartData = (function () {
  40538. function GroupInfoPartData(stride) {
  40539. this._partData = null;
  40540. this._partBuffer = null;
  40541. this._partBufferSize = 0;
  40542. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  40543. this._isDisposed = false;
  40544. }
  40545. GroupInfoPartData.prototype.dispose = function (engine) {
  40546. if (this._isDisposed) {
  40547. return false;
  40548. }
  40549. if (this._partBuffer) {
  40550. engine._releaseBuffer(this._partBuffer);
  40551. this._partBuffer = null;
  40552. }
  40553. this._partData = null;
  40554. this._isDisposed = true;
  40555. };
  40556. return GroupInfoPartData;
  40557. })();
  40558. BABYLON.GroupInfoPartData = GroupInfoPartData;
  40559. var TransparentGroupInfoPartData = (function (_super) {
  40560. __extends(TransparentGroupInfoPartData, _super);
  40561. function TransparentGroupInfoPartData(stride, zoff) {
  40562. _super.call(this, stride);
  40563. this._partData.compareValueOffset = zoff;
  40564. this._partData.sortingAscending = false;
  40565. }
  40566. return TransparentGroupInfoPartData;
  40567. })(GroupInfoPartData);
  40568. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  40569. var ModelRenderCache = (function () {
  40570. function ModelRenderCache(engine, modelKey) {
  40571. this._engine = engine;
  40572. this._modelKey = modelKey;
  40573. this._nextKey = 1;
  40574. this._refCounter = 1;
  40575. this._instancesData = new BABYLON.StringDictionary();
  40576. this._partData = null;
  40577. }
  40578. ModelRenderCache.prototype.dispose = function () {
  40579. if (--this._refCounter !== 0) {
  40580. return false;
  40581. }
  40582. // Remove the Model Render Cache from the global dictionary
  40583. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  40584. if (edata) {
  40585. edata.DisposeModelRenderCache(this);
  40586. }
  40587. return true;
  40588. };
  40589. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  40590. get: function () {
  40591. return this._refCounter <= 0;
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. ModelRenderCache.prototype.addRef = function () {
  40597. return ++this._refCounter;
  40598. };
  40599. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  40600. get: function () {
  40601. return this._modelKey;
  40602. },
  40603. enumerable: true,
  40604. configurable: true
  40605. });
  40606. /**
  40607. * Render the model instances
  40608. * @param instanceInfo
  40609. * @param context
  40610. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  40611. */
  40612. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  40613. return true;
  40614. };
  40615. ModelRenderCache.prototype.addInstanceDataParts = function (data) {
  40616. var key = this._nextKey.toString();
  40617. if (!this._instancesData.add(key, data)) {
  40618. throw Error("Key: " + key + " is already allocated");
  40619. }
  40620. ++this._nextKey;
  40621. return key;
  40622. };
  40623. ModelRenderCache.prototype.removeInstanceData = function (key) {
  40624. this._instancesData.remove(key);
  40625. };
  40626. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  40627. for (var i = 0; i < this._partData.length; i++) {
  40628. if (this._partData[i]._partId === partId) {
  40629. return i;
  40630. }
  40631. }
  40632. return null;
  40633. };
  40634. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  40635. var i = this.getPartIndexFromId(partId);
  40636. if (i === null) {
  40637. return null;
  40638. }
  40639. var ci = this._partsClassInfo[i];
  40640. var categories = this._partData[i]._partUsedCategories;
  40641. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  40642. return res;
  40643. };
  40644. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  40645. var pd = this._partData[partIndex];
  40646. var offset = (pd._partDataStride / 4) * elementCount;
  40647. var pci = this._partsClassInfo[partIndex];
  40648. var self = this;
  40649. pci.fullContent.forEach(function (k, v) {
  40650. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  40651. switch (v.dataType) {
  40652. case 4 /* float */:
  40653. {
  40654. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40655. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  40656. break;
  40657. }
  40658. case 0 /* Vector2 */:
  40659. {
  40660. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40661. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  40662. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  40663. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  40664. break;
  40665. }
  40666. case 5 /* Color3 */:
  40667. case 1 /* Vector3 */:
  40668. {
  40669. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40670. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  40671. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  40672. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  40673. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  40674. break;
  40675. }
  40676. case 6 /* Color4 */:
  40677. case 2 /* Vector4 */:
  40678. {
  40679. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  40680. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  40681. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  40682. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  40683. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  40684. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  40685. break;
  40686. }
  40687. default:
  40688. }
  40689. }
  40690. });
  40691. };
  40692. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  40693. // let i = this.getPartIndexFromId(partId);
  40694. // if (i === null) {
  40695. // return null;
  40696. // }
  40697. // let pci = this._partsClassInfo[i];
  40698. // pci.fullContent.forEach((k, v) => {
  40699. // if (uniforms.indexOf(v.attributeName) !== -1) {
  40700. // v.uniformLocation = effect.getUniform(v.attributeName);
  40701. // }
  40702. // });
  40703. //}
  40704. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  40705. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  40706. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  40707. return ModelRenderCache;
  40708. })();
  40709. BABYLON.ModelRenderCache = ModelRenderCache;
  40710. var ModelRenderCachePartData = (function () {
  40711. function ModelRenderCachePartData() {
  40712. }
  40713. return ModelRenderCachePartData;
  40714. })();
  40715. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  40716. })(BABYLON || (BABYLON = {}));
  40717. var BABYLON;
  40718. (function (BABYLON) {
  40719. var InstanceClassInfo = (function () {
  40720. function InstanceClassInfo(base) {
  40721. this._baseInfo = base;
  40722. this._nextOffset = new BABYLON.StringDictionary();
  40723. this._attributes = new Array();
  40724. }
  40725. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  40726. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  40727. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  40728. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  40729. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  40730. if (push) {
  40731. this._attributes.push(propInfo);
  40732. }
  40733. };
  40734. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  40735. var catInline = ";" + categories.join(";") + ";";
  40736. var res = new Array();
  40737. var curInfo = this;
  40738. while (curInfo) {
  40739. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40740. var attrib = _a[_i];
  40741. // 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
  40742. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40743. var index = effect.getAttributeLocationByName(attrib.attributeName);
  40744. var iai = new BABYLON.InstancingAttributeInfo();
  40745. iai.index = index;
  40746. 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)
  40747. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  40748. iai.attributeName = attrib.attributeName;
  40749. res.push(iai);
  40750. }
  40751. }
  40752. curInfo = curInfo._baseInfo;
  40753. }
  40754. return res;
  40755. };
  40756. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  40757. var res = new Array();
  40758. var curInfo = this;
  40759. while (curInfo) {
  40760. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  40761. var attrib = _a[_i];
  40762. // 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
  40763. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  40764. res.push(attrib.attributeName);
  40765. }
  40766. }
  40767. curInfo = curInfo._baseInfo;
  40768. }
  40769. return res;
  40770. };
  40771. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  40772. var curOffset = 0;
  40773. var curBase = this._baseInfo;
  40774. while (curBase) {
  40775. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  40776. curBase = curBase._baseInfo;
  40777. }
  40778. return curOffset;
  40779. };
  40780. return InstanceClassInfo;
  40781. })();
  40782. BABYLON.InstanceClassInfo = InstanceClassInfo;
  40783. var InstancePropInfo = (function () {
  40784. function InstancePropInfo() {
  40785. this.instanceOffset = new BABYLON.StringDictionary();
  40786. }
  40787. InstancePropInfo.prototype.setSize = function (val) {
  40788. if (val instanceof BABYLON.Vector2) {
  40789. this.size = 8;
  40790. this.dataType = 0 /* Vector2 */;
  40791. return;
  40792. }
  40793. if (val instanceof BABYLON.Vector3) {
  40794. this.size = 12;
  40795. this.dataType = 1 /* Vector3 */;
  40796. return;
  40797. }
  40798. if (val instanceof BABYLON.Vector4) {
  40799. this.size = 16;
  40800. this.dataType = 2 /* Vector4 */;
  40801. return;
  40802. }
  40803. if (val instanceof BABYLON.Matrix) {
  40804. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  40805. }
  40806. if (typeof (val) === "number") {
  40807. this.size = 4;
  40808. this.dataType = 4 /* float */;
  40809. return;
  40810. }
  40811. if (val instanceof BABYLON.Color3) {
  40812. this.size = 12;
  40813. this.dataType = 5 /* Color3 */;
  40814. return;
  40815. }
  40816. if (val instanceof BABYLON.Color4) {
  40817. this.size = 16;
  40818. this.dataType = 6 /* Color4 */;
  40819. return;
  40820. }
  40821. if (val instanceof BABYLON.Size) {
  40822. this.size = 8;
  40823. this.dataType = 7 /* Size */;
  40824. return;
  40825. }
  40826. return;
  40827. };
  40828. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  40829. switch (this.dataType) {
  40830. case 0 /* Vector2 */:
  40831. {
  40832. var v = val;
  40833. array[offset + 0] = v.x;
  40834. array[offset + 1] = v.y;
  40835. break;
  40836. }
  40837. case 1 /* Vector3 */:
  40838. {
  40839. var v = val;
  40840. array[offset + 0] = v.x;
  40841. array[offset + 1] = v.y;
  40842. array[offset + 2] = v.z;
  40843. break;
  40844. }
  40845. case 2 /* Vector4 */:
  40846. {
  40847. var v = val;
  40848. array[offset + 0] = v.x;
  40849. array[offset + 1] = v.y;
  40850. array[offset + 2] = v.z;
  40851. array[offset + 3] = v.w;
  40852. break;
  40853. }
  40854. case 5 /* Color3 */:
  40855. {
  40856. var v = val;
  40857. array[offset + 0] = v.r;
  40858. array[offset + 1] = v.g;
  40859. array[offset + 2] = v.b;
  40860. break;
  40861. }
  40862. case 6 /* Color4 */:
  40863. {
  40864. var v = val;
  40865. array[offset + 0] = v.r;
  40866. array[offset + 1] = v.g;
  40867. array[offset + 2] = v.b;
  40868. array[offset + 3] = v.a;
  40869. break;
  40870. }
  40871. case 4 /* float */:
  40872. {
  40873. var v = val;
  40874. array[offset] = v;
  40875. break;
  40876. }
  40877. case 3 /* Matrix */:
  40878. {
  40879. var v = val;
  40880. for (var i = 0; i < 16; i++) {
  40881. array[offset + i] = v.m[i];
  40882. }
  40883. break;
  40884. }
  40885. case 7 /* Size */:
  40886. {
  40887. var s = val;
  40888. array[offset + 0] = s.width;
  40889. array[offset + 1] = s.height;
  40890. break;
  40891. }
  40892. }
  40893. };
  40894. return InstancePropInfo;
  40895. })();
  40896. BABYLON.InstancePropInfo = InstancePropInfo;
  40897. function instanceData(category, shaderAttributeName) {
  40898. return function (target, propName, descriptor) {
  40899. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  40900. var node = dic.getLevelOf(target);
  40901. var instanceDataName = propName;
  40902. shaderAttributeName = shaderAttributeName || instanceDataName;
  40903. var info = node.levelContent.get(instanceDataName);
  40904. if (info) {
  40905. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  40906. }
  40907. info = new InstancePropInfo();
  40908. info.attributeName = shaderAttributeName;
  40909. info.category = category || null;
  40910. if (info.category) {
  40911. info.delimitedCategory = ";" + info.category + ";";
  40912. }
  40913. node.levelContent.add(instanceDataName, info);
  40914. descriptor.get = function () {
  40915. return null;
  40916. };
  40917. descriptor.set = function (val) {
  40918. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  40919. // Quit if it's the case, otherwise we could overwrite data somewhere...
  40920. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  40921. return;
  40922. }
  40923. if (!info.size) {
  40924. info.setSize(val);
  40925. node.classContent.mapProperty(info, true);
  40926. }
  40927. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  40928. node.classContent.mapProperty(info, false);
  40929. }
  40930. var obj = this;
  40931. if (obj.dataBuffer && obj.dataElements) {
  40932. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  40933. info.writeData(obj.dataBuffer.buffer, offset, val);
  40934. }
  40935. };
  40936. };
  40937. }
  40938. BABYLON.instanceData = instanceData;
  40939. var InstanceDataBase = (function () {
  40940. function InstanceDataBase(partId, dataElementCount) {
  40941. this.id = partId;
  40942. this.curElement = 0;
  40943. this.dataElementCount = dataElementCount;
  40944. this.renderMode = 0;
  40945. this.arrayLengthChanged = false;
  40946. }
  40947. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  40948. get: function () {
  40949. return null;
  40950. },
  40951. enumerable: true,
  40952. configurable: true
  40953. });
  40954. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  40955. get: function () {
  40956. return null;
  40957. },
  40958. enumerable: true,
  40959. configurable: true
  40960. });
  40961. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  40962. get: function () {
  40963. return null;
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  40969. get: function () {
  40970. return null;
  40971. },
  40972. enumerable: true,
  40973. configurable: true
  40974. });
  40975. InstanceDataBase.prototype.getClassTreeInfo = function () {
  40976. if (!this.typeInfo) {
  40977. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  40978. }
  40979. return this.typeInfo;
  40980. };
  40981. InstanceDataBase.prototype.allocElements = function () {
  40982. if (!this.dataBuffer || this.dataElements) {
  40983. return;
  40984. }
  40985. var res = new Array(this.dataElementCount);
  40986. for (var i = 0; i < this.dataElementCount; i++) {
  40987. res[i] = this.dataBuffer.allocElement();
  40988. }
  40989. this.dataElements = res;
  40990. };
  40991. InstanceDataBase.prototype.freeElements = function () {
  40992. if (!this.dataElements) {
  40993. return;
  40994. }
  40995. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  40996. var ei = _a[_i];
  40997. this.dataBuffer.freeElement(ei);
  40998. }
  40999. this.dataElements = null;
  41000. };
  41001. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  41002. get: function () {
  41003. return this._dataElementCount;
  41004. },
  41005. set: function (value) {
  41006. if (value === this._dataElementCount) {
  41007. return;
  41008. }
  41009. this.arrayLengthChanged = true;
  41010. this.freeElements();
  41011. this._dataElementCount = value;
  41012. this.allocElements();
  41013. },
  41014. enumerable: true,
  41015. configurable: true
  41016. });
  41017. __decorate([
  41018. instanceData()
  41019. ], InstanceDataBase.prototype, "zBias", null);
  41020. __decorate([
  41021. instanceData()
  41022. ], InstanceDataBase.prototype, "transformX", null);
  41023. __decorate([
  41024. instanceData()
  41025. ], InstanceDataBase.prototype, "transformY", null);
  41026. __decorate([
  41027. instanceData()
  41028. ], InstanceDataBase.prototype, "opacity", null);
  41029. return InstanceDataBase;
  41030. })();
  41031. BABYLON.InstanceDataBase = InstanceDataBase;
  41032. var RenderablePrim2D = (function (_super) {
  41033. __extends(RenderablePrim2D, _super);
  41034. function RenderablePrim2D(settings) {
  41035. _super.call(this, settings);
  41036. this._isTransparent = false;
  41037. this._isAlphaTest = false;
  41038. this._transparentPrimitiveInfo = null;
  41039. }
  41040. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  41041. get: function () {
  41042. return this._isAlphaTest;
  41043. },
  41044. set: function (value) {
  41045. if (this._isAlphaTest === value) {
  41046. return;
  41047. }
  41048. this._isAlphaTest = value;
  41049. this._updateRenderMode();
  41050. },
  41051. enumerable: true,
  41052. configurable: true
  41053. });
  41054. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  41055. get: function () {
  41056. return this._isTransparent || (this._opacity < 1);
  41057. },
  41058. set: function (value) {
  41059. if (this._isTransparent === value) {
  41060. return;
  41061. }
  41062. this._isTransparent = value;
  41063. this._updateRenderMode();
  41064. },
  41065. enumerable: true,
  41066. configurable: true
  41067. });
  41068. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  41069. get: function () {
  41070. return this._renderMode;
  41071. },
  41072. enumerable: true,
  41073. configurable: true
  41074. });
  41075. /**
  41076. * Dispose the primitive and its resources, remove it from its parent
  41077. */
  41078. RenderablePrim2D.prototype.dispose = function () {
  41079. if (!_super.prototype.dispose.call(this)) {
  41080. return false;
  41081. }
  41082. if (this._transparentPrimitiveInfo) {
  41083. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41084. this._transparentPrimitiveInfo = null;
  41085. }
  41086. if (this._modelRenderInstanceID) {
  41087. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41088. this._modelRenderInstanceID = null;
  41089. }
  41090. if (this._modelRenderCache) {
  41091. this._modelRenderCache.dispose();
  41092. this._modelRenderCache = null;
  41093. }
  41094. if (this._instanceDataParts) {
  41095. this._instanceDataParts.forEach(function (p) {
  41096. p.freeElements();
  41097. });
  41098. this._instanceDataParts = null;
  41099. }
  41100. return true;
  41101. };
  41102. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  41103. _super.prototype._prepareRenderPre.call(this, context);
  41104. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  41105. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._modelRenderInstanceID) {
  41106. this._modelRenderCache.removeInstanceData(this._modelRenderInstanceID);
  41107. this._modelRenderInstanceID = null;
  41108. }
  41109. // Need to create the model?
  41110. var setupModelRenderCache = false;
  41111. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  41112. setupModelRenderCache = this._createModelRenderCache();
  41113. }
  41114. var gii = null;
  41115. var newInstance = false;
  41116. // Need to create the instance data parts?
  41117. if (!this._modelRenderInstanceID) {
  41118. // Yes, flag it for later, more processing will have to be done
  41119. newInstance = true;
  41120. gii = this._createModelDataParts();
  41121. }
  41122. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  41123. if (setupModelRenderCache) {
  41124. this.setupModelRenderCache(this._modelRenderCache);
  41125. }
  41126. // 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.
  41127. // 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.
  41128. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep)) {
  41129. this._updateInstanceDataParts(gii);
  41130. }
  41131. };
  41132. RenderablePrim2D.prototype._createModelRenderCache = function () {
  41133. var _this = this;
  41134. var setupModelRenderCache = false;
  41135. if (this._modelRenderCache) {
  41136. this._modelRenderCache.dispose();
  41137. }
  41138. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  41139. var mrc = _this.createModelRenderCache(key);
  41140. setupModelRenderCache = true;
  41141. return mrc;
  41142. });
  41143. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41144. // if this is still false it means the MRC already exists, so we add a reference to it
  41145. if (!setupModelRenderCache) {
  41146. this._modelRenderCache.addRef();
  41147. }
  41148. return setupModelRenderCache;
  41149. };
  41150. RenderablePrim2D.prototype._createModelDataParts = function () {
  41151. var _this = this;
  41152. // Create the instance data parts of the primitive and store them
  41153. var parts = this.createInstanceDataParts();
  41154. this._instanceDataParts = parts;
  41155. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  41156. if (!this._modelRenderCache._partData) {
  41157. this._setupModelRenderCache(parts);
  41158. }
  41159. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  41160. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  41161. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  41162. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  41163. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  41164. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  41165. var part = _this._instanceDataParts[j];
  41166. res.partIndexFromId.add(part.id.toString(), j);
  41167. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  41168. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  41169. }
  41170. return res;
  41171. });
  41172. // Get the GroupInfoDataPart corresponding to the render category of the part
  41173. var rm = 0;
  41174. var gipd = null;
  41175. if (this.isTransparent) {
  41176. gipd = gii.transparentData;
  41177. rm = BABYLON.Render2DContext.RenderModeTransparent;
  41178. }
  41179. else if (this.isAlphaTest) {
  41180. gipd = gii.alphaTestData;
  41181. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  41182. }
  41183. else {
  41184. gipd = gii.opaqueData;
  41185. rm = BABYLON.Render2DContext.RenderModeOpaque;
  41186. }
  41187. // For each instance data part of the primitive, allocate the instanced element it needs for render
  41188. for (var i = 0; i < parts.length; i++) {
  41189. var part = parts[i];
  41190. part.dataBuffer = gipd[i]._partData;
  41191. part.allocElements();
  41192. part.renderMode = rm;
  41193. }
  41194. // 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
  41195. this._modelRenderInstanceID = this._modelRenderCache.addInstanceDataParts(this._instanceDataParts);
  41196. return gii;
  41197. };
  41198. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  41199. var ctiArray = new Array();
  41200. this._modelRenderCache._partData = new Array();
  41201. for (var _i = 0; _i < parts.length; _i++) {
  41202. var dataPart = parts[_i];
  41203. var pd = new BABYLON.ModelRenderCachePartData();
  41204. this._modelRenderCache._partData.push(pd);
  41205. var cat = this.getUsedShaderCategories(dataPart);
  41206. var cti = dataPart.getClassTreeInfo();
  41207. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  41208. var curVisible = this.isVisible;
  41209. this.isVisible = true;
  41210. // 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.
  41211. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  41212. var joinCat = ";" + cat.join(";") + ";";
  41213. pd._partJoinedUsedCategories = joinCat;
  41214. InstanceClassInfo._CurCategories = joinCat;
  41215. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  41216. if (!this.refreshInstanceDataPart(dataPart)) {
  41217. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  41218. }
  41219. this.afterRefreshForLayoutConstruction(dataPart, obj);
  41220. this.isVisible = curVisible;
  41221. var size = 0;
  41222. cti.fullContent.forEach(function (k, v) {
  41223. if (!v.category || cat.indexOf(v.category) !== -1) {
  41224. if (v.attributeName === "zBias") {
  41225. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  41226. }
  41227. if (!v.size) {
  41228. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  41229. }
  41230. else {
  41231. size += v.size;
  41232. }
  41233. }
  41234. });
  41235. pd._partDataStride = size;
  41236. pd._partUsedCategories = cat;
  41237. pd._partId = dataPart.id;
  41238. ctiArray.push(cti);
  41239. }
  41240. this._modelRenderCache._partsClassInfo = ctiArray;
  41241. };
  41242. RenderablePrim2D.prototype.onZOrderChanged = function () {
  41243. if (this.isTransparent && this._transparentPrimitiveInfo) {
  41244. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  41245. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  41246. // Flag the transparentData dirty has will have to sort it again
  41247. gii.transparentOrderDirty = true;
  41248. }
  41249. };
  41250. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  41251. // Fetch the GroupInstanceInfo if we don't already have it
  41252. var rd = this.renderGroup._renderableData;
  41253. if (!gii) {
  41254. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  41255. }
  41256. var isTransparent = this.isTransparent;
  41257. var isAlphaTest = this.isAlphaTest;
  41258. var wereTransparent = false;
  41259. // Check a render mode change
  41260. var rmChanged = false;
  41261. if (this._instanceDataParts.length > 0) {
  41262. var firstPart = this._instanceDataParts[0];
  41263. var partRM = firstPart.renderMode;
  41264. var curRM = this.renderMode;
  41265. if (partRM !== curRM) {
  41266. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  41267. rmChanged = true;
  41268. var gipd;
  41269. switch (curRM) {
  41270. case BABYLON.Render2DContext.RenderModeTransparent:
  41271. gipd = gii.transparentData;
  41272. break;
  41273. case BABYLON.Render2DContext.RenderModeAlphaTest:
  41274. gipd = gii.alphaTestData;
  41275. break;
  41276. default:
  41277. gipd = gii.opaqueData;
  41278. }
  41279. for (var i = 0; i < this._instanceDataParts.length; i++) {
  41280. var part = this._instanceDataParts[i];
  41281. part.freeElements();
  41282. part.dataBuffer = gipd[i]._partData;
  41283. part.renderMode = curRM;
  41284. }
  41285. }
  41286. }
  41287. // Handle changes related to ZOffset
  41288. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  41289. if (isTransparent || wereTransparent) {
  41290. // Handle visibility change, which is also triggered when the primitive just got created
  41291. if (visChanged || rmChanged) {
  41292. if (this.isVisible && !wereTransparent) {
  41293. if (!this._transparentPrimitiveInfo) {
  41294. // Add the primitive to the list of transparent ones in the group that render is
  41295. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  41296. }
  41297. }
  41298. else {
  41299. if (this._transparentPrimitiveInfo) {
  41300. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  41301. this._transparentPrimitiveInfo = null;
  41302. }
  41303. }
  41304. gii.transparentOrderDirty = true;
  41305. }
  41306. }
  41307. var rebuildTrans = false;
  41308. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  41309. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41310. var part = _a[_i];
  41311. var justAllocated = false;
  41312. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  41313. if (visChanged || !part.dataElements || rmChanged) {
  41314. part.allocElements();
  41315. justAllocated = true;
  41316. }
  41317. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  41318. // Will return false if the instance should not be rendered (not visible or other any reasons)
  41319. part.arrayLengthChanged = false;
  41320. if (!this.refreshInstanceDataPart(part)) {
  41321. // Free the data element
  41322. if (part.dataElements) {
  41323. part.freeElements();
  41324. }
  41325. }
  41326. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  41327. }
  41328. this._instanceDirtyFlags = 0;
  41329. // Make the appropriate data dirty
  41330. if (isTransparent) {
  41331. gii.transparentDirty = true;
  41332. if (rebuildTrans) {
  41333. rd._transparentListChanged = true;
  41334. }
  41335. }
  41336. else if (isAlphaTest) {
  41337. gii.alphaTestDirty = true;
  41338. }
  41339. else {
  41340. gii.opaqueDirty = true;
  41341. }
  41342. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  41343. };
  41344. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  41345. var minOff = BABYLON.Prim2DBase._bigInt;
  41346. var maxOff = 0;
  41347. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41348. var part = _a[_i];
  41349. if (part && part.dataElements) {
  41350. part.dataBuffer.pack();
  41351. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41352. var el = _c[_b];
  41353. minOff = Math.min(minOff, el.offset);
  41354. maxOff = Math.max(maxOff, el.offset);
  41355. }
  41356. ts.startDataIndex = minOff / part.dataBuffer.stride;
  41357. ts.endDataIndex = (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41358. }
  41359. }
  41360. };
  41361. RenderablePrim2D.prototype._getPrimitiveLastIndex = function () {
  41362. var maxOff = 0;
  41363. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  41364. var part = _a[_i];
  41365. if (part) {
  41366. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  41367. var el = _c[_b];
  41368. maxOff = Math.max(maxOff, el.offset);
  41369. }
  41370. return (maxOff / part.dataBuffer.stride) + 1; // +1 for exclusive
  41371. }
  41372. }
  41373. };
  41374. // This internal method is mainly used for transparency processing
  41375. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  41376. var length = this._instanceDataParts.length;
  41377. for (var i = 0; i < length; i++) {
  41378. var part = this._instanceDataParts[i];
  41379. if (part) {
  41380. var stride = part.dataBuffer.stride;
  41381. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  41382. // check if it's the last in the DFA
  41383. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  41384. return null;
  41385. }
  41386. // Return the Z of the next primitive that lies in the DFA
  41387. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41388. }
  41389. }
  41390. return null;
  41391. };
  41392. // This internal method is mainly used for transparency processing
  41393. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  41394. var length = this._instanceDataParts.length;
  41395. for (var i = 0; i < length; i++) {
  41396. var part = this._instanceDataParts[i];
  41397. if (part) {
  41398. var stride = part.dataBuffer.stride;
  41399. var firstElementOffset = part.dataElements[0].offset;
  41400. // check if it's the first in the DFA
  41401. if (firstElementOffset === 0) {
  41402. return null;
  41403. }
  41404. // Return the Z of the previous primitive that lies in the DFA
  41405. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  41406. }
  41407. }
  41408. return null;
  41409. };
  41410. /**
  41411. * Transform a given point using the Primitive's origin setting.
  41412. * This method requires the Primitive's actualSize to be accurate
  41413. * @param p the point to transform
  41414. * @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.
  41415. * @param res an allocated Vector2 that will receive the transformed content
  41416. */
  41417. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  41418. var actualSize = this.actualSize;
  41419. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  41420. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  41421. };
  41422. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  41423. this.transformPointWithOriginByRef(p, originOffset, res);
  41424. return res;
  41425. };
  41426. /**
  41427. * Get the info for a given effect based on the dataPart metadata
  41428. * @param dataPartId partId in part list to get the info
  41429. * @param vertexBufferAttributes vertex buffer attributes to manually add
  41430. * @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
  41431. */
  41432. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, useInstanced) {
  41433. if (useInstanced === void 0) { useInstanced = null; }
  41434. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  41435. if (!dataPart) {
  41436. return null;
  41437. }
  41438. var instancedArray = this.owner.supportInstancedArray;
  41439. if (useInstanced != null) {
  41440. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  41441. if (useInstanced && instancedArray === false) {
  41442. return null;
  41443. }
  41444. // Use the caller's setting
  41445. instancedArray = useInstanced;
  41446. }
  41447. var cti = dataPart.getClassTreeInfo();
  41448. var categories = this.getUsedShaderCategories(dataPart);
  41449. var att = cti.classContent.getShaderAttributes(categories);
  41450. var defines = "";
  41451. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  41452. if (instancedArray) {
  41453. defines += "#define Instanced\n";
  41454. }
  41455. return { attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes, uniforms: instancedArray ? [] : att, defines: defines };
  41456. };
  41457. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  41458. get: function () {
  41459. return this._modelRenderCache;
  41460. },
  41461. enumerable: true,
  41462. configurable: true
  41463. });
  41464. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  41465. return null;
  41466. };
  41467. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  41468. };
  41469. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  41470. return null;
  41471. };
  41472. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  41473. return [];
  41474. };
  41475. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  41476. };
  41477. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  41478. };
  41479. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  41480. if (!this.isVisible) {
  41481. return false;
  41482. }
  41483. part.isVisible = this.isVisible;
  41484. // 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)
  41485. if (part.dataElementCount === 1) {
  41486. part.curElement = 0;
  41487. this.updateInstanceDataPart(part);
  41488. }
  41489. return true;
  41490. };
  41491. /**
  41492. * Update the instanceDataBase level properties of a part
  41493. * @param part the part to update
  41494. * @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).
  41495. */
  41496. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  41497. if (positionOffset === void 0) { positionOffset = null; }
  41498. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  41499. var size = this.renderGroup.viewportSize;
  41500. var zBias = this.actualZOffset;
  41501. var offX = 0;
  41502. var offY = 0;
  41503. // If there's an offset, apply the global transformation matrix on it to get a global offset
  41504. if (positionOffset) {
  41505. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  41506. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  41507. }
  41508. // 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
  41509. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  41510. // So for X:
  41511. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  41512. // - 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].
  41513. var w = size.width;
  41514. var h = size.height;
  41515. var invZBias = 1 / zBias;
  41516. 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);
  41517. 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);
  41518. part.transformX = tx;
  41519. part.transformY = ty;
  41520. part.opacity = this.actualOpacity;
  41521. // 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)
  41522. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  41523. };
  41524. RenderablePrim2D.prototype._updateRenderMode = function () {
  41525. if (this.isTransparent) {
  41526. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  41527. }
  41528. else if (this.isAlphaTest) {
  41529. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  41530. }
  41531. else {
  41532. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  41533. }
  41534. };
  41535. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  41536. __decorate([
  41537. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  41538. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  41539. __decorate([
  41540. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  41541. ], RenderablePrim2D.prototype, "isTransparent", null);
  41542. RenderablePrim2D = __decorate([
  41543. BABYLON.className("RenderablePrim2D")
  41544. ], RenderablePrim2D);
  41545. return RenderablePrim2D;
  41546. })(BABYLON.Prim2DBase);
  41547. BABYLON.RenderablePrim2D = RenderablePrim2D;
  41548. })(BABYLON || (BABYLON = {}));
  41549. var BABYLON;
  41550. (function (BABYLON) {
  41551. var Shape2D = (function (_super) {
  41552. __extends(Shape2D, _super);
  41553. function Shape2D(settings) {
  41554. _super.call(this, settings);
  41555. if (!settings) {
  41556. settings = {};
  41557. }
  41558. var borderBrush = null;
  41559. if (settings.border) {
  41560. if (typeof (settings.border) === "string") {
  41561. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  41562. }
  41563. else {
  41564. borderBrush = settings.border;
  41565. }
  41566. }
  41567. var fillBrush = null;
  41568. if (settings.fill) {
  41569. if (typeof (settings.fill) === "string") {
  41570. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  41571. }
  41572. else {
  41573. fillBrush = settings.fill;
  41574. }
  41575. }
  41576. this.border = borderBrush;
  41577. this.fill = fillBrush;
  41578. this.borderThickness = settings.borderThickness;
  41579. }
  41580. Object.defineProperty(Shape2D.prototype, "border", {
  41581. get: function () {
  41582. return this._border;
  41583. },
  41584. set: function (value) {
  41585. this._border = value;
  41586. this._updateTransparencyStatus();
  41587. },
  41588. enumerable: true,
  41589. configurable: true
  41590. });
  41591. Object.defineProperty(Shape2D.prototype, "fill", {
  41592. /**
  41593. * Get/set the brush to render the Fill part of the Primitive
  41594. */
  41595. get: function () {
  41596. return this._fill;
  41597. },
  41598. set: function (value) {
  41599. this._fill = value;
  41600. this._updateTransparencyStatus();
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  41606. get: function () {
  41607. return this._borderThickness;
  41608. },
  41609. set: function (value) {
  41610. this._borderThickness = value;
  41611. },
  41612. enumerable: true,
  41613. configurable: true
  41614. });
  41615. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  41616. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  41617. // Fill Part
  41618. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  41619. var fill = this.fill;
  41620. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41621. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  41622. }
  41623. if (fill instanceof BABYLON.GradientColorBrush2D) {
  41624. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  41625. }
  41626. }
  41627. // Border Part
  41628. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41629. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  41630. var border = this.border;
  41631. if (border instanceof BABYLON.SolidColorBrush2D) {
  41632. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  41633. }
  41634. if (border instanceof BABYLON.GradientColorBrush2D) {
  41635. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  41636. }
  41637. }
  41638. return cat;
  41639. };
  41640. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  41641. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  41642. return false;
  41643. }
  41644. // Fill Part
  41645. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  41646. var d = part;
  41647. if (this.fill) {
  41648. var fill = this.fill;
  41649. if (fill instanceof BABYLON.SolidColorBrush2D) {
  41650. d.fillSolidColor = fill.color;
  41651. }
  41652. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  41653. d.fillGradientColor1 = fill.color1;
  41654. d.fillGradientColor2 = fill.color2;
  41655. 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));
  41656. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41657. d.fillGradientTY = ty;
  41658. }
  41659. }
  41660. }
  41661. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  41662. var d = part;
  41663. if (this.border) {
  41664. d.borderThickness = this.borderThickness;
  41665. var border = this.border;
  41666. if (border instanceof BABYLON.SolidColorBrush2D) {
  41667. d.borderSolidColor = border.color;
  41668. }
  41669. else if (border instanceof BABYLON.GradientColorBrush2D) {
  41670. d.borderGradientColor1 = border.color1;
  41671. d.borderGradientColor2 = border.color2;
  41672. 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));
  41673. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  41674. d.borderGradientTY = ty;
  41675. }
  41676. }
  41677. }
  41678. return true;
  41679. };
  41680. Shape2D.prototype._updateTransparencyStatus = function () {
  41681. this.isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  41682. };
  41683. Shape2D.SHAPE2D_BORDERPARTID = 1;
  41684. Shape2D.SHAPE2D_FILLPARTID = 2;
  41685. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  41686. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  41687. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  41688. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  41689. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  41690. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  41691. __decorate([
  41692. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  41693. ], Shape2D.prototype, "border", null);
  41694. __decorate([
  41695. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  41696. ], Shape2D.prototype, "fill", null);
  41697. __decorate([
  41698. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  41699. ], Shape2D.prototype, "borderThickness", null);
  41700. Shape2D = __decorate([
  41701. BABYLON.className("Shape2D")
  41702. ], Shape2D);
  41703. return Shape2D;
  41704. })(BABYLON.RenderablePrim2D);
  41705. BABYLON.Shape2D = Shape2D;
  41706. var Shape2DInstanceData = (function (_super) {
  41707. __extends(Shape2DInstanceData, _super);
  41708. function Shape2DInstanceData() {
  41709. _super.apply(this, arguments);
  41710. }
  41711. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  41712. // FILL ATTRIBUTES
  41713. get: function () {
  41714. return null;
  41715. },
  41716. enumerable: true,
  41717. configurable: true
  41718. });
  41719. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  41720. get: function () {
  41721. return null;
  41722. },
  41723. enumerable: true,
  41724. configurable: true
  41725. });
  41726. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  41727. get: function () {
  41728. return null;
  41729. },
  41730. enumerable: true,
  41731. configurable: true
  41732. });
  41733. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  41734. get: function () {
  41735. return null;
  41736. },
  41737. enumerable: true,
  41738. configurable: true
  41739. });
  41740. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  41741. // BORDER ATTRIBUTES
  41742. get: function () {
  41743. return null;
  41744. },
  41745. enumerable: true,
  41746. configurable: true
  41747. });
  41748. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  41749. get: function () {
  41750. return null;
  41751. },
  41752. enumerable: true,
  41753. configurable: true
  41754. });
  41755. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  41756. get: function () {
  41757. return null;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  41763. get: function () {
  41764. return null;
  41765. },
  41766. enumerable: true,
  41767. configurable: true
  41768. });
  41769. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  41770. get: function () {
  41771. return null;
  41772. },
  41773. enumerable: true,
  41774. configurable: true
  41775. });
  41776. __decorate([
  41777. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  41778. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  41779. __decorate([
  41780. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41781. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  41782. __decorate([
  41783. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41784. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  41785. __decorate([
  41786. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  41787. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  41788. __decorate([
  41789. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  41790. ], Shape2DInstanceData.prototype, "borderThickness", null);
  41791. __decorate([
  41792. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  41793. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  41794. __decorate([
  41795. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41796. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  41797. __decorate([
  41798. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41799. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  41800. __decorate([
  41801. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  41802. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  41803. return Shape2DInstanceData;
  41804. })(BABYLON.InstanceDataBase);
  41805. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  41806. })(BABYLON || (BABYLON = {}));
  41807. var BABYLON;
  41808. (function (BABYLON) {
  41809. var Group2D = (function (_super) {
  41810. __extends(Group2D, _super);
  41811. /**
  41812. * Create an Logical or Renderable Group.
  41813. * @param settings a combination of settings, possible ones are
  41814. * - 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)
  41815. * - children: an array of direct children
  41816. * - id a text identifier, for information purpose
  41817. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  41818. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  41819. * - scale: the initial scale of the primitive. default is 1
  41820. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  41821. * - origin: define the normalized origin point location, default [0.5;0.5]
  41822. * - 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.
  41823. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  41824. * - 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).
  41825. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  41826. * - 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!
  41827. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41828. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41829. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41830. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41831. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  41832. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  41833. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  41834. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  41835. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41836. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41837. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41838. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  41839. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  41840. */
  41841. function Group2D(settings) {
  41842. if (settings == null) {
  41843. settings = {};
  41844. }
  41845. if (settings.origin == null) {
  41846. settings.origin = new BABYLON.Vector2(0, 0);
  41847. }
  41848. _super.call(this, settings);
  41849. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  41850. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  41851. if (this._trackedNode && this.owner) {
  41852. this.owner._registerTrackedNode(this);
  41853. }
  41854. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  41855. this.size = size;
  41856. this._viewportPosition = BABYLON.Vector2.Zero();
  41857. }
  41858. Group2D._createCachedCanvasGroup = function (owner) {
  41859. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true });
  41860. return g;
  41861. };
  41862. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  41863. this._bindCacheTarget();
  41864. if (vertexData) {
  41865. var uv = vertexData.uvs;
  41866. var nodeuv = this._renderableData._cacheNodeUVs;
  41867. for (var i = 0; i < 4; i++) {
  41868. uv[i * 2 + 0] = nodeuv[i].x;
  41869. uv[i * 2 + 1] = nodeuv[i].y;
  41870. }
  41871. }
  41872. if (material) {
  41873. material.diffuseTexture = this._renderableData._cacheTexture;
  41874. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41875. }
  41876. this._renderableData._cacheTexture.hasAlpha = true;
  41877. this._unbindCacheTarget();
  41878. };
  41879. Object.defineProperty(Group2D.prototype, "cachedRect", {
  41880. /**
  41881. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  41882. * 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.
  41883. */
  41884. get: function () {
  41885. if (!this._renderableData) {
  41886. return null;
  41887. }
  41888. return this._renderableData._cacheNode;
  41889. },
  41890. enumerable: true,
  41891. configurable: true
  41892. });
  41893. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  41894. /**
  41895. * The UVs into the MapTexture that map the cached group
  41896. */
  41897. get: function () {
  41898. if (!this._renderableData) {
  41899. return null;
  41900. }
  41901. return this._renderableData._cacheNodeUVs;
  41902. },
  41903. enumerable: true,
  41904. configurable: true
  41905. });
  41906. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  41907. get: function () {
  41908. if (!this._renderableData) {
  41909. return null;
  41910. }
  41911. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  41912. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  41913. }
  41914. return this._renderableData._cacheNodeUVsChangedObservable;
  41915. },
  41916. enumerable: true,
  41917. configurable: true
  41918. });
  41919. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  41920. /**
  41921. * Access the texture that maintains a cached version of the Group2D.
  41922. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  41923. */
  41924. get: function () {
  41925. if (!this._renderableData) {
  41926. return null;
  41927. }
  41928. return this._renderableData._cacheTexture;
  41929. },
  41930. enumerable: true,
  41931. configurable: true
  41932. });
  41933. /**
  41934. * Call this method to remove this Group and its children from the Canvas
  41935. */
  41936. Group2D.prototype.dispose = function () {
  41937. if (!_super.prototype.dispose.call(this)) {
  41938. return false;
  41939. }
  41940. if (this._trackedNode != null) {
  41941. this.owner._unregisterTrackedNode(this);
  41942. this._trackedNode = null;
  41943. }
  41944. if (this._renderableData) {
  41945. this._renderableData.dispose(this.owner.engine);
  41946. this._renderableData = null;
  41947. }
  41948. return true;
  41949. };
  41950. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  41951. /**
  41952. * @returns Returns true if the Group render content, false if it's a logical group only
  41953. */
  41954. get: function () {
  41955. return this._isRenderableGroup;
  41956. },
  41957. enumerable: true,
  41958. configurable: true
  41959. });
  41960. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  41961. /**
  41962. * @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
  41963. */
  41964. get: function () {
  41965. return this._isCachedGroup;
  41966. },
  41967. enumerable: true,
  41968. configurable: true
  41969. });
  41970. Object.defineProperty(Group2D.prototype, "size", {
  41971. get: function () {
  41972. return this._size;
  41973. },
  41974. /**
  41975. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  41976. * 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.
  41977. */
  41978. set: function (val) {
  41979. this._size = val;
  41980. },
  41981. enumerable: true,
  41982. configurable: true
  41983. });
  41984. Object.defineProperty(Group2D.prototype, "viewportSize", {
  41985. get: function () {
  41986. return this._viewportSize;
  41987. },
  41988. enumerable: true,
  41989. configurable: true
  41990. });
  41991. Object.defineProperty(Group2D.prototype, "actualSize", {
  41992. get: function () {
  41993. // The computed size will be floor on both width and height
  41994. var actualSize;
  41995. // Return the size if set by the user
  41996. if (this._size) {
  41997. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  41998. }
  41999. else {
  42000. var m = this.boundingInfo.max();
  42001. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  42002. }
  42003. // 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)
  42004. if (!actualSize.equals(this._actualSize)) {
  42005. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  42006. this._actualSize = actualSize;
  42007. this.handleGroupChanged(Group2D.actualSizeProperty);
  42008. }
  42009. return actualSize;
  42010. },
  42011. enumerable: true,
  42012. configurable: true
  42013. });
  42014. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  42015. /**
  42016. * 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.
  42017. * 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.
  42018. */
  42019. get: function () {
  42020. return this._cacheBehavior;
  42021. },
  42022. enumerable: true,
  42023. configurable: true
  42024. });
  42025. Group2D.prototype._addPrimToDirtyList = function (prim) {
  42026. this._renderableData._primDirtyList.push(prim);
  42027. };
  42028. Group2D.prototype._renderCachedCanvas = function () {
  42029. this.owner._addGroupRenderCount(1);
  42030. this.updateCachedStates(true);
  42031. var context = new BABYLON.PrepareRender2DContext();
  42032. this._prepareGroupRender(context);
  42033. this._groupRender();
  42034. };
  42035. Object.defineProperty(Group2D.prototype, "trackedNode", {
  42036. /**
  42037. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  42038. */
  42039. get: function () {
  42040. return this._trackedNode;
  42041. },
  42042. set: function (val) {
  42043. if (val != null) {
  42044. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42045. this.owner._registerTrackedNode(this);
  42046. }
  42047. this._trackedNode = val;
  42048. }
  42049. else {
  42050. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  42051. this.owner._unregisterTrackedNode(this);
  42052. }
  42053. this._trackedNode = null;
  42054. }
  42055. },
  42056. enumerable: true,
  42057. configurable: true
  42058. });
  42059. Group2D.prototype.levelIntersect = function (intersectInfo) {
  42060. // 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
  42061. return true;
  42062. };
  42063. Group2D.prototype.updateLevelBoundingInfo = function () {
  42064. var size;
  42065. // If the size is set by the user, the boundingInfo is computed from this value
  42066. if (this.size) {
  42067. size = this.size;
  42068. }
  42069. else {
  42070. size = new BABYLON.Size(0, 0);
  42071. }
  42072. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  42073. };
  42074. // Method called only on renderable groups to prepare the rendering
  42075. Group2D.prototype._prepareGroupRender = function (context) {
  42076. var sortedDirtyList = null;
  42077. // Update the Global Transformation and visibility status of the changed primitives
  42078. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42079. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42080. this.updateCachedStatesOf(sortedDirtyList, true);
  42081. }
  42082. // Setup the size of the rendering viewport
  42083. // 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
  42084. if (!this._isCachedGroup) {
  42085. // Compute the WebGL viewport's location/size
  42086. var t = this._globalTransform.getTranslation();
  42087. var s = this.actualSize.clone();
  42088. var rs = this.owner._renderingSize;
  42089. s.height = Math.min(s.height, rs.height - t.y);
  42090. s.width = Math.min(s.width, rs.width - t.x);
  42091. var x = t.x;
  42092. var y = t.y;
  42093. // 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
  42094. this._viewportPosition.x = x;
  42095. this._viewportPosition.y = y;
  42096. var vw = s.width;
  42097. var vh = s.height;
  42098. if (!this._viewportSize) {
  42099. this._viewportSize = new BABYLON.Size(vw, vh);
  42100. }
  42101. else {
  42102. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  42103. context.forceRefreshPrimitive = true;
  42104. }
  42105. this._viewportSize.width = vw;
  42106. this._viewportSize.height = vh;
  42107. }
  42108. }
  42109. else {
  42110. var newSize = this.actualSize.clone();
  42111. if (!newSize.equals(this._viewportSize)) {
  42112. context.forceRefreshPrimitive = true;
  42113. }
  42114. this._viewportSize = newSize;
  42115. }
  42116. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  42117. // If the group is cached, set the dirty flag to true because of the incoming changes
  42118. this._cacheGroupDirty = this._isCachedGroup;
  42119. // If it's a force refresh, prepare all the children
  42120. if (context.forceRefreshPrimitive) {
  42121. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  42122. var p = _a[_i];
  42123. p._prepareRender(context);
  42124. }
  42125. }
  42126. else {
  42127. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  42128. // the hierarchyDepth in order to prepare primitives from top to bottom
  42129. if (!sortedDirtyList) {
  42130. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  42131. }
  42132. sortedDirtyList.forEach(function (p) {
  42133. // 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.
  42134. // 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.
  42135. if (!p.isDisposed && p._needPrepare()) {
  42136. p._prepareRender(context);
  42137. }
  42138. });
  42139. // Everything is updated, clear the dirty list
  42140. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  42141. this._renderableData._primDirtyList.splice(0);
  42142. }
  42143. }
  42144. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  42145. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  42146. g._prepareGroupRender(context);
  42147. });
  42148. };
  42149. Group2D.prototype._groupRender = function () {
  42150. var _this = this;
  42151. var engine = this.owner.engine;
  42152. var failedCount = 0;
  42153. // First recurse to children render group to render them (in their cache or on screen)
  42154. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  42155. var childGroup = _a[_i];
  42156. childGroup._groupRender();
  42157. }
  42158. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  42159. if (!this.isCachedGroup || this._cacheGroupDirty) {
  42160. this.owner._addGroupRenderCount(1);
  42161. if (this.isCachedGroup) {
  42162. this._bindCacheTarget();
  42163. }
  42164. else {
  42165. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  42166. }
  42167. var curAlphaTest = engine.getAlphaTesting() === true;
  42168. var curDepthWrite = engine.getDepthWrite() === true;
  42169. // ===================================================================
  42170. // First pass, update the InstancedArray and render Opaque primitives
  42171. // Disable Alpha Testing, Enable Depth Write
  42172. engine.setAlphaTesting(false);
  42173. engine.setDepthWrite(true);
  42174. // For each different model of primitive to render
  42175. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  42176. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42177. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42178. var renderCount = _this._prepareContext(engine, context, v);
  42179. // If null is returned, there's no opaque data to render
  42180. if (renderCount === null) {
  42181. return;
  42182. }
  42183. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42184. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42185. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42186. var renderFailed = !v.modelRenderCache.render(v, context);
  42187. // Update dirty flag/related
  42188. v.opaqueDirty = renderFailed;
  42189. failedCount += renderFailed ? 1 : 0;
  42190. }
  42191. });
  42192. // =======================================================================
  42193. // Second pass, update the InstancedArray and render AlphaTest primitives
  42194. // Enable Alpha Testing, Enable Depth Write
  42195. engine.setAlphaTesting(true);
  42196. engine.setDepthWrite(true);
  42197. // For each different model of primitive to render
  42198. context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  42199. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  42200. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  42201. var renderCount = _this._prepareContext(engine, context, v);
  42202. // If null is returned, there's no opaque data to render
  42203. if (renderCount === null) {
  42204. return;
  42205. }
  42206. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  42207. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  42208. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  42209. var renderFailed = !v.modelRenderCache.render(v, context);
  42210. // Update dirty flag/related
  42211. v.opaqueDirty = renderFailed;
  42212. failedCount += renderFailed ? 1 : 0;
  42213. }
  42214. });
  42215. // =======================================================================
  42216. // Third pass, transparent primitive rendering
  42217. // Enable Alpha Testing, Disable Depth Write
  42218. engine.setAlphaTesting(true);
  42219. engine.setDepthWrite(false);
  42220. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  42221. if (this._renderableData._transparentListChanged) {
  42222. this._updateTransparentData();
  42223. }
  42224. // From this point on we have up to date data to render, so let's go
  42225. failedCount += this._renderTransparentData();
  42226. // =======================================================================
  42227. // Unbind target/restore viewport setting, clear dirty flag, and quit
  42228. // The group's content is no longer dirty
  42229. this._cacheGroupDirty = failedCount !== 0;
  42230. if (this.isCachedGroup) {
  42231. this._unbindCacheTarget();
  42232. }
  42233. else {
  42234. if (curVP) {
  42235. engine.setViewport(curVP);
  42236. }
  42237. }
  42238. // Restore saved states
  42239. engine.setAlphaTesting(curAlphaTest);
  42240. engine.setDepthWrite(curDepthWrite);
  42241. }
  42242. };
  42243. Group2D.prototype._updateTransparentData = function () {
  42244. this.owner._addUpdateTransparentDataCount(1);
  42245. var rd = this._renderableData;
  42246. // Sort all the primitive from their depth, max (bottom) to min (top)
  42247. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  42248. var checkAndAddPrimInSegment = function (seg, tpiI) {
  42249. var tpi = rd._transparentPrimitives[tpiI];
  42250. // Fast rejection: if gii are different
  42251. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  42252. return false;
  42253. }
  42254. //let tpiZ = tpi._primitive.actualZOffset;
  42255. // We've made it so far, the tpi can be part of the segment, add it
  42256. tpi._transparentSegment = seg;
  42257. seg.endDataIndex = tpi._primitive._getPrimitiveLastIndex();
  42258. return true;
  42259. };
  42260. // Free the existing TransparentSegments
  42261. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  42262. var ts = _a[_i];
  42263. ts.dispose(this.owner.engine);
  42264. }
  42265. rd._transparentSegments.splice(0);
  42266. var prevSeg = null;
  42267. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  42268. var tpi = rd._transparentPrimitives[tpiI];
  42269. // Check if the Data in which the primitive is stored is not sorted properly
  42270. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  42271. tpi._groupInstanceInfo.sortTransparentData();
  42272. }
  42273. // Reset the segment, we have to create/rebuild it
  42274. tpi._transparentSegment = null;
  42275. // If there's a previous valid segment, check if this prim can be part of it
  42276. if (prevSeg) {
  42277. checkAndAddPrimInSegment(prevSeg, tpiI);
  42278. }
  42279. // If we couldn't insert in the adjacent segments, he have to create one
  42280. if (!tpi._transparentSegment) {
  42281. var ts = new BABYLON.TransparentSegment();
  42282. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  42283. var prim = tpi._primitive;
  42284. ts.startZ = prim.actualZOffset;
  42285. prim._updateTransparentSegmentIndices(ts);
  42286. ts.endZ = ts.startZ;
  42287. tpi._transparentSegment = ts;
  42288. rd._transparentSegments.push(ts);
  42289. }
  42290. // Update prevSeg
  42291. prevSeg = tpi._transparentSegment;
  42292. }
  42293. //rd._firstChangedPrim = null;
  42294. rd._transparentListChanged = false;
  42295. };
  42296. Group2D.prototype._renderTransparentData = function () {
  42297. var failedCount = 0;
  42298. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  42299. var rd = this._renderableData;
  42300. var useInstanced = this.owner.supportInstancedArray;
  42301. var length = rd._transparentSegments.length;
  42302. for (var i = 0; i < length; i++) {
  42303. context.instancedBuffers = null;
  42304. var ts = rd._transparentSegments[i];
  42305. var gii = ts.groupInsanceInfo;
  42306. var mrc = gii.modelRenderCache;
  42307. var engine = this.owner.engine;
  42308. var count = ts.endDataIndex - ts.startDataIndex;
  42309. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  42310. // We don't want to create an Instanced Buffer for less that 5 prims
  42311. if (useInstanced && count >= 5) {
  42312. if (!ts.partBuffers) {
  42313. var buffers = new Array();
  42314. for (var j = 0; j < gii.transparentData.length; j++) {
  42315. var gitd = gii.transparentData[j];
  42316. var dfa = gitd._partData;
  42317. var data = dfa.pack();
  42318. var stride = dfa.stride;
  42319. var neededSize = count * stride * 4;
  42320. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42321. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42322. engine.updateArrayBuffer(segData);
  42323. buffers.push(buffer);
  42324. }
  42325. ts.partBuffers = buffers;
  42326. }
  42327. else if (gii.transparentDirty) {
  42328. for (var j = 0; j < gii.transparentData.length; j++) {
  42329. var gitd = gii.transparentData[j];
  42330. var dfa = gitd._partData;
  42331. var data = dfa.pack();
  42332. var stride = dfa.stride;
  42333. var buffer = ts.partBuffers[j];
  42334. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  42335. engine.bindArrayBuffer(buffer);
  42336. engine.updateArrayBuffer(segData);
  42337. }
  42338. }
  42339. context.useInstancing = true;
  42340. context.instancesCount = count;
  42341. context.instancedBuffers = ts.partBuffers;
  42342. context.groupInfoPartData = gii.transparentData;
  42343. var renderFailed = !mrc.render(gii, context);
  42344. failedCount += renderFailed ? 1 : 0;
  42345. }
  42346. else {
  42347. context.useInstancing = false;
  42348. context.partDataStartIndex = ts.startDataIndex;
  42349. context.partDataEndIndex = ts.endDataIndex;
  42350. context.groupInfoPartData = gii.transparentData;
  42351. var renderFailed = !mrc.render(gii, context);
  42352. failedCount += renderFailed ? 1 : 0;
  42353. }
  42354. }
  42355. return failedCount;
  42356. };
  42357. Group2D.prototype._prepareContext = function (engine, context, gii) {
  42358. var gipd = null;
  42359. var setDirty;
  42360. var getDirty;
  42361. // Render Mode specifics
  42362. switch (context.renderMode) {
  42363. case BABYLON.Render2DContext.RenderModeOpaque:
  42364. {
  42365. if (!gii.hasOpaqueData) {
  42366. return null;
  42367. }
  42368. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  42369. getDirty = function () { return gii.opaqueDirty; };
  42370. context.groupInfoPartData = gii.opaqueData;
  42371. gipd = gii.opaqueData;
  42372. break;
  42373. }
  42374. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42375. {
  42376. if (!gii.hasAlphaTestData) {
  42377. return null;
  42378. }
  42379. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  42380. getDirty = function () { return gii.alphaTestDirty; };
  42381. context.groupInfoPartData = gii.alphaTestData;
  42382. gipd = gii.alphaTestData;
  42383. break;
  42384. }
  42385. default:
  42386. throw new Error("_prepareContext is only for opaque or alphaTest");
  42387. }
  42388. var renderCount = 0;
  42389. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  42390. // Skip it if instanced arrays are not supported
  42391. if (this.owner.supportInstancedArray) {
  42392. // Flag for instancing
  42393. context.useInstancing = true;
  42394. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  42395. for (var i = 0; i < gipd.length; i++) {
  42396. var pid = gipd[i];
  42397. // If the instances of the model was changed, pack the data
  42398. var array = pid._partData;
  42399. var instanceData_1 = array.pack();
  42400. renderCount += array.usedElementCount;
  42401. // Compute the size the instance buffer should have
  42402. var neededSize = array.usedElementCount * array.stride * 4;
  42403. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  42404. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  42405. if (pid._partBuffer) {
  42406. engine.deleteInstancesBuffer(pid._partBuffer);
  42407. }
  42408. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  42409. pid._partBufferSize = neededSize;
  42410. setDirty(false);
  42411. // Update the WebGL buffer to match the new content of the instances data
  42412. engine.updateArrayBuffer(instanceData_1);
  42413. }
  42414. else if (getDirty()) {
  42415. // Update the WebGL buffer to match the new content of the instances data
  42416. engine.bindArrayBuffer(pid._partBuffer);
  42417. engine.updateArrayBuffer(instanceData_1);
  42418. }
  42419. }
  42420. setDirty(false);
  42421. }
  42422. else {
  42423. context.partDataStartIndex = 0;
  42424. // Find the first valid object to get the count
  42425. if (context.groupInfoPartData.length > 0) {
  42426. var i = 0;
  42427. while (!context.groupInfoPartData[i]) {
  42428. i++;
  42429. }
  42430. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  42431. }
  42432. }
  42433. return renderCount;
  42434. };
  42435. Group2D.prototype._setRenderingScale = function (scale) {
  42436. if (this._renderableData._renderingScale === scale) {
  42437. return;
  42438. }
  42439. this._renderableData._renderingScale = scale;
  42440. };
  42441. Group2D.prototype._bindCacheTarget = function () {
  42442. var curWidth;
  42443. var curHeight;
  42444. var rd = this._renderableData;
  42445. var rs = rd._renderingScale;
  42446. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  42447. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  42448. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  42449. if (rd._cacheNode) {
  42450. var size = rd._cacheNode.contentSize;
  42451. // Check if we have to deallocate because the size is too small
  42452. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  42453. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  42454. // For World space: no over-provisioning
  42455. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  42456. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  42457. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  42458. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  42459. rd._cacheTexture.freeRect(rd._cacheNode);
  42460. rd._cacheNode = null;
  42461. }
  42462. }
  42463. if (!rd._cacheNode) {
  42464. // Check if we have to allocate a rendering zone in the global cache texture
  42465. var res = this.owner._allocateGroupCache(this, this.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  42466. rd._cacheNode = res.node;
  42467. rd._cacheTexture = res.texture;
  42468. rd._cacheRenderSprite = res.sprite;
  42469. sizeChanged = true;
  42470. }
  42471. if (sizeChanged) {
  42472. rd._cacheSize.copyFrom(Group2D._s);
  42473. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  42474. this.scale = this._renderableData._renderingScale;
  42475. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  42476. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  42477. }
  42478. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  42479. }
  42480. var n = rd._cacheNode;
  42481. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  42482. };
  42483. Group2D.prototype._unbindCacheTarget = function () {
  42484. if (this._renderableData._cacheTexture) {
  42485. this._renderableData._cacheTexture.unbindTexture();
  42486. }
  42487. };
  42488. Group2D.prototype.handleGroupChanged = function (prop) {
  42489. // This method is only for cachedGroup
  42490. var rd = this._renderableData;
  42491. if (!this.isCachedGroup || !rd._cacheRenderSprite) {
  42492. return;
  42493. }
  42494. // For now we only support these property changes
  42495. // TODO: add more! :)
  42496. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  42497. rd._cacheRenderSprite.actualPosition = this.actualPosition.clone();
  42498. }
  42499. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  42500. rd._cacheRenderSprite.rotation = this.rotation;
  42501. }
  42502. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  42503. rd._cacheRenderSprite.scale = this.scale;
  42504. }
  42505. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  42506. rd._cacheRenderSprite.origin = this.origin.clone();
  42507. }
  42508. else if (prop.id === Group2D.actualSizeProperty.id) {
  42509. rd._cacheRenderSprite.size = this.actualSize.clone();
  42510. }
  42511. };
  42512. Group2D.prototype.detectGroupStates = function () {
  42513. var isCanvas = this instanceof BABYLON.Canvas2D;
  42514. var canvasStrat = this.owner.cachingStrategy;
  42515. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  42516. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  42517. this._isRenderableGroup = isCanvas;
  42518. this._isCachedGroup = false;
  42519. }
  42520. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  42521. if (isCanvas) {
  42522. this._isRenderableGroup = true;
  42523. this._isCachedGroup = true;
  42524. }
  42525. else {
  42526. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  42527. this._isCachedGroup = false;
  42528. }
  42529. }
  42530. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  42531. if (isCanvas) {
  42532. this._isRenderableGroup = true;
  42533. this._isCachedGroup = false;
  42534. }
  42535. else {
  42536. if (this.hierarchyDepth === 1) {
  42537. this._isRenderableGroup = true;
  42538. this._isCachedGroup = true;
  42539. }
  42540. else {
  42541. this._isRenderableGroup = false;
  42542. this._isCachedGroup = false;
  42543. }
  42544. }
  42545. }
  42546. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  42547. var gcb = this.cacheBehavior;
  42548. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  42549. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  42550. this._isCachedGroup = false;
  42551. }
  42552. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  42553. this._isRenderableGroup = true;
  42554. this._isCachedGroup = true;
  42555. }
  42556. }
  42557. if (this._isRenderableGroup) {
  42558. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  42559. if (!this._renderableData) {
  42560. this._renderableData = new RenderableGroupData();
  42561. }
  42562. }
  42563. // If the group is tagged as renderable we add it to the renderable tree
  42564. if (this._isCachedGroup) {
  42565. var cur = this.parent;
  42566. while (cur) {
  42567. if (cur instanceof Group2D && cur._isRenderableGroup) {
  42568. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  42569. cur._renderableData._childrenRenderableGroups.push(this);
  42570. }
  42571. break;
  42572. }
  42573. cur = cur.parent;
  42574. }
  42575. }
  42576. };
  42577. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  42578. /**
  42579. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  42580. */
  42581. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  42582. /**
  42583. * When used, this group's content won't be cached, no matter which strategy used.
  42584. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  42585. */
  42586. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  42587. /**
  42588. * When used, the group's content will be cached in the nearest cached parent group/canvas
  42589. */
  42590. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  42591. Group2D._s = BABYLON.Size.Zero();
  42592. __decorate([
  42593. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  42594. ], Group2D.prototype, "size", null);
  42595. __decorate([
  42596. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  42597. ], Group2D.prototype, "actualSize", null);
  42598. Group2D = __decorate([
  42599. BABYLON.className("Group2D")
  42600. ], Group2D);
  42601. return Group2D;
  42602. })(BABYLON.Prim2DBase);
  42603. BABYLON.Group2D = Group2D;
  42604. var RenderableGroupData = (function () {
  42605. function RenderableGroupData() {
  42606. this._primDirtyList = new Array();
  42607. this._childrenRenderableGroups = new Array();
  42608. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  42609. this._transparentPrimitives = new Array();
  42610. this._transparentSegments = new Array();
  42611. this._transparentListChanged = false;
  42612. this._cacheNode = null;
  42613. this._cacheTexture = null;
  42614. this._cacheRenderSprite = null;
  42615. this._renderingScale = 1;
  42616. this._cacheNodeUVs = null;
  42617. this._cacheNodeUVsChangedObservable = null;
  42618. this._cacheSize = BABYLON.Size.Zero();
  42619. this._useMipMap = false;
  42620. this._anisotropicLevel = 1;
  42621. }
  42622. RenderableGroupData.prototype.dispose = function (engine) {
  42623. if (this._cacheRenderSprite) {
  42624. this._cacheRenderSprite.dispose();
  42625. this._cacheRenderSprite = null;
  42626. }
  42627. if (this._cacheTexture && this._cacheNode) {
  42628. this._cacheTexture.freeRect(this._cacheNode);
  42629. this._cacheTexture = null;
  42630. this._cacheNode = null;
  42631. }
  42632. if (this._primDirtyList) {
  42633. this._primDirtyList.splice(0);
  42634. this._primDirtyList = null;
  42635. }
  42636. if (this._renderGroupInstancesInfo) {
  42637. this._renderGroupInstancesInfo.forEach(function (k, v) {
  42638. v.dispose();
  42639. });
  42640. this._renderGroupInstancesInfo = null;
  42641. }
  42642. if (this._cacheNodeUVsChangedObservable) {
  42643. this._cacheNodeUVsChangedObservable.clear();
  42644. this._cacheNodeUVsChangedObservable = null;
  42645. }
  42646. if (this._transparentSegments) {
  42647. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  42648. var ts = _a[_i];
  42649. ts.dispose(engine);
  42650. }
  42651. this._transparentSegments.splice(0);
  42652. this._transparentSegments = null;
  42653. }
  42654. };
  42655. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  42656. var tpi = new TransparentPrimitiveInfo();
  42657. tpi._primitive = prim;
  42658. tpi._groupInstanceInfo = gii;
  42659. tpi._transparentSegment = null;
  42660. this._transparentPrimitives.push(tpi);
  42661. this._transparentListChanged = true;
  42662. return tpi;
  42663. };
  42664. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  42665. var index = this._transparentPrimitives.indexOf(tpi);
  42666. if (index !== -1) {
  42667. this._transparentPrimitives.splice(index, 1);
  42668. this._transparentListChanged = true;
  42669. }
  42670. };
  42671. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  42672. this._transparentListChanged = true;
  42673. //this.updateSmallestZChangedPrim(tpi);
  42674. };
  42675. return RenderableGroupData;
  42676. })();
  42677. BABYLON.RenderableGroupData = RenderableGroupData;
  42678. var TransparentPrimitiveInfo = (function () {
  42679. function TransparentPrimitiveInfo() {
  42680. }
  42681. return TransparentPrimitiveInfo;
  42682. })();
  42683. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  42684. })(BABYLON || (BABYLON = {}));
  42685. var BABYLON;
  42686. (function (BABYLON) {
  42687. var Rectangle2DRenderCache = (function (_super) {
  42688. __extends(Rectangle2DRenderCache, _super);
  42689. function Rectangle2DRenderCache(engine, modelKey) {
  42690. _super.call(this, engine, modelKey);
  42691. this.effectsReady = false;
  42692. this.fillVB = null;
  42693. this.fillIB = null;
  42694. this.fillIndicesCount = 0;
  42695. this.instancingFillAttributes = null;
  42696. this.effectFill = null;
  42697. this.effectFillInstanced = null;
  42698. this.borderVB = null;
  42699. this.borderIB = null;
  42700. this.borderIndicesCount = 0;
  42701. this.instancingBorderAttributes = null;
  42702. this.effectBorder = null;
  42703. this.effectBorderInstanced = null;
  42704. }
  42705. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  42706. // Do nothing if the shader is still loading/preparing
  42707. if (!this.effectsReady) {
  42708. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  42709. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  42710. return false;
  42711. }
  42712. this.effectsReady = true;
  42713. }
  42714. var canvas = instanceInfo.owner.owner;
  42715. var engine = canvas.engine;
  42716. var depthFunction = 0;
  42717. if (this.effectFill && this.effectBorder) {
  42718. depthFunction = engine.getDepthFunction();
  42719. engine.setDepthFunctionToLessOrEqual();
  42720. }
  42721. var curAlphaMode = engine.getAlphaMode();
  42722. if (this.effectFill) {
  42723. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  42724. var pid = context.groupInfoPartData[partIndex];
  42725. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42726. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42727. }
  42728. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  42729. engine.enableEffect(effect);
  42730. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  42731. if (context.useInstancing) {
  42732. if (!this.instancingFillAttributes) {
  42733. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  42734. }
  42735. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42736. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42737. canvas._addDrawCallCount(1, context.renderMode);
  42738. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  42739. engine.draw(true, 0, this.fillIndicesCount, count);
  42740. engine.unbindInstanceAttributes();
  42741. }
  42742. else {
  42743. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42744. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42745. this.setupUniforms(effect, partIndex, pid._partData, i);
  42746. engine.draw(true, 0, this.fillIndicesCount);
  42747. }
  42748. }
  42749. }
  42750. if (this.effectBorder) {
  42751. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  42752. var pid = context.groupInfoPartData[partIndex];
  42753. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  42754. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42755. }
  42756. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  42757. engine.enableEffect(effect);
  42758. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  42759. if (context.useInstancing) {
  42760. if (!this.instancingBorderAttributes) {
  42761. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  42762. }
  42763. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  42764. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  42765. canvas._addDrawCallCount(1, context.renderMode);
  42766. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  42767. engine.draw(true, 0, this.borderIndicesCount, count);
  42768. engine.unbindInstanceAttributes();
  42769. }
  42770. else {
  42771. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  42772. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  42773. this.setupUniforms(effect, partIndex, pid._partData, i);
  42774. engine.draw(true, 0, this.borderIndicesCount);
  42775. }
  42776. }
  42777. }
  42778. engine.setAlphaMode(curAlphaMode);
  42779. if (this.effectFill && this.effectBorder) {
  42780. engine.setDepthFunction(depthFunction);
  42781. }
  42782. return true;
  42783. };
  42784. Rectangle2DRenderCache.prototype.dispose = function () {
  42785. if (!_super.prototype.dispose.call(this)) {
  42786. return false;
  42787. }
  42788. if (this.fillVB) {
  42789. this._engine._releaseBuffer(this.fillVB);
  42790. this.fillVB = null;
  42791. }
  42792. if (this.fillIB) {
  42793. this._engine._releaseBuffer(this.fillIB);
  42794. this.fillIB = null;
  42795. }
  42796. if (this.effectFill) {
  42797. this._engine._releaseEffect(this.effectFill);
  42798. this.effectFill = null;
  42799. }
  42800. if (this.effectFillInstanced) {
  42801. this._engine._releaseEffect(this.effectFillInstanced);
  42802. this.effectFillInstanced = null;
  42803. }
  42804. if (this.borderVB) {
  42805. this._engine._releaseBuffer(this.borderVB);
  42806. this.borderVB = null;
  42807. }
  42808. if (this.borderIB) {
  42809. this._engine._releaseBuffer(this.borderIB);
  42810. this.borderIB = null;
  42811. }
  42812. if (this.effectBorder) {
  42813. this._engine._releaseEffect(this.effectBorder);
  42814. this.effectBorder = null;
  42815. }
  42816. if (this.effectBorderInstanced) {
  42817. this._engine._releaseEffect(this.effectBorderInstanced);
  42818. this.effectBorderInstanced = null;
  42819. }
  42820. return true;
  42821. };
  42822. return Rectangle2DRenderCache;
  42823. })(BABYLON.ModelRenderCache);
  42824. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  42825. var Rectangle2DInstanceData = (function (_super) {
  42826. __extends(Rectangle2DInstanceData, _super);
  42827. function Rectangle2DInstanceData(partId) {
  42828. _super.call(this, partId, 1);
  42829. }
  42830. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  42831. get: function () {
  42832. return null;
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. __decorate([
  42838. BABYLON.instanceData()
  42839. ], Rectangle2DInstanceData.prototype, "properties", null);
  42840. return Rectangle2DInstanceData;
  42841. })(BABYLON.Shape2DInstanceData);
  42842. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  42843. var Rectangle2D = (function (_super) {
  42844. __extends(Rectangle2D, _super);
  42845. /**
  42846. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  42847. * @param settings a combination of settings, possible ones are
  42848. * - 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)
  42849. * - children: an array of direct children
  42850. * - id a text identifier, for information purpose
  42851. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  42852. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  42853. * - scale: the initial scale of the primitive. default is 1
  42854. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  42855. * - origin: define the normalized origin point location, default [0.5;0.5]
  42856. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  42857. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  42858. * - 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)
  42859. * - 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)
  42860. * - borderThickness: the thickness of the drawn border, default is 1.
  42861. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  42862. * - 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!
  42863. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42864. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42865. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42866. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42867. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  42868. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  42869. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  42870. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  42871. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42872. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42873. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42874. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  42875. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  42876. */
  42877. function Rectangle2D(settings) {
  42878. // Avoid checking every time if the object exists
  42879. if (settings == null) {
  42880. settings = {};
  42881. }
  42882. _super.call(this, settings);
  42883. if (settings.size != null) {
  42884. this.size = settings.size;
  42885. }
  42886. else if (settings.width || settings.height) {
  42887. var size = new BABYLON.Size(settings.width, settings.height);
  42888. this.size = size;
  42889. }
  42890. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  42891. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  42892. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  42893. //this.size = size;
  42894. this.roundRadius = roundRadius;
  42895. this.borderThickness = borderThickness;
  42896. }
  42897. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  42898. get: function () {
  42899. if (this._actualSize) {
  42900. return this._actualSize;
  42901. }
  42902. return this.size;
  42903. },
  42904. set: function (value) {
  42905. this._actualSize = value;
  42906. },
  42907. enumerable: true,
  42908. configurable: true
  42909. });
  42910. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  42911. get: function () {
  42912. return this._notRounded;
  42913. },
  42914. set: function (value) {
  42915. this._notRounded = value;
  42916. },
  42917. enumerable: true,
  42918. configurable: true
  42919. });
  42920. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  42921. get: function () {
  42922. return this._roundRadius;
  42923. },
  42924. set: function (value) {
  42925. this._roundRadius = value;
  42926. this.notRounded = value === 0;
  42927. this._positioningDirty();
  42928. },
  42929. enumerable: true,
  42930. configurable: true
  42931. });
  42932. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  42933. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  42934. if (this.notRounded) {
  42935. return true;
  42936. }
  42937. // 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.
  42938. // 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)
  42939. // 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.
  42940. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  42941. var size = this.size;
  42942. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  42943. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  42944. var rr = this.roundRadius;
  42945. var rrs = rr * rr;
  42946. // Check if the point is in the bottom/left quarter area
  42947. Rectangle2D._i1.x = rr;
  42948. Rectangle2D._i1.y = rr;
  42949. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42950. // Compute the intersection point in the quarter local space
  42951. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42952. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42953. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42954. return Rectangle2D._i2.lengthSquared() <= rrs;
  42955. }
  42956. // Check if the point is in the top/left quarter area
  42957. Rectangle2D._i1.x = rr;
  42958. Rectangle2D._i1.y = size.height - rr;
  42959. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42960. // Compute the intersection point in the quarter local space
  42961. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42962. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42963. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42964. return Rectangle2D._i2.lengthSquared() <= rrs;
  42965. }
  42966. // Check if the point is in the top/right quarter area
  42967. Rectangle2D._i1.x = size.width - rr;
  42968. Rectangle2D._i1.y = size.height - rr;
  42969. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  42970. // Compute the intersection point in the quarter local space
  42971. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42972. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42973. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42974. return Rectangle2D._i2.lengthSquared() <= rrs;
  42975. }
  42976. // Check if the point is in the bottom/right quarter area
  42977. Rectangle2D._i1.x = size.width - rr;
  42978. Rectangle2D._i1.y = rr;
  42979. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  42980. // Compute the intersection point in the quarter local space
  42981. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  42982. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  42983. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  42984. return Rectangle2D._i2.lengthSquared() <= rrs;
  42985. }
  42986. // At any other locations the point is guarantied to be inside
  42987. return true;
  42988. };
  42989. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  42990. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  42991. };
  42992. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  42993. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  42994. return renderCache;
  42995. };
  42996. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42997. var renderCache = modelRenderCache;
  42998. var engine = this.owner.engine;
  42999. // Need to create WebGL resources for fill part?
  43000. if (this.fill) {
  43001. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  43002. var vb = new Float32Array(vbSize);
  43003. for (var i = 0; i < vbSize; i++) {
  43004. vb[i] = i;
  43005. }
  43006. renderCache.fillVB = engine.createVertexBuffer(vb);
  43007. var triCount = vbSize - 1;
  43008. var ib = new Float32Array(triCount * 3);
  43009. for (var i = 0; i < triCount; i++) {
  43010. ib[i * 3 + 0] = 0;
  43011. ib[i * 3 + 2] = i + 1;
  43012. ib[i * 3 + 1] = i + 2;
  43013. }
  43014. ib[triCount * 3 - 2] = 1;
  43015. renderCache.fillIB = engine.createIndexBuffer(ib);
  43016. renderCache.fillIndicesCount = triCount * 3;
  43017. // 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
  43018. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43019. if (ei) {
  43020. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43021. }
  43022. // Get the non instanced version
  43023. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43024. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43025. }
  43026. // Need to create WebGL resource for border part?
  43027. if (this.border) {
  43028. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  43029. var vb = new Float32Array(vbSize);
  43030. for (var i = 0; i < vbSize; i++) {
  43031. vb[i] = i;
  43032. }
  43033. renderCache.borderVB = engine.createVertexBuffer(vb);
  43034. var triCount = vbSize;
  43035. var rs = triCount / 2;
  43036. var ib = new Float32Array(triCount * 3);
  43037. for (var i = 0; i < rs; i++) {
  43038. var r0 = i;
  43039. var r1 = (i + 1) % rs;
  43040. ib[i * 6 + 0] = rs + r1;
  43041. ib[i * 6 + 1] = rs + r0;
  43042. ib[i * 6 + 2] = r0;
  43043. ib[i * 6 + 3] = r1;
  43044. ib[i * 6 + 4] = rs + r1;
  43045. ib[i * 6 + 5] = r0;
  43046. }
  43047. renderCache.borderIB = engine.createIndexBuffer(ib);
  43048. renderCache.borderIndicesCount = triCount * 3;
  43049. // 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
  43050. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43051. if (ei) {
  43052. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43053. }
  43054. // Get the non instanced version
  43055. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43056. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43057. }
  43058. return renderCache;
  43059. };
  43060. // 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
  43061. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  43062. // Fall back to default implementation if there's no round Radius
  43063. if (this._notRounded) {
  43064. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  43065. }
  43066. else {
  43067. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  43068. initialContentPosition.x = initialContentPosition.y = rr;
  43069. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  43070. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  43071. }
  43072. };
  43073. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  43074. // Fall back to default implementation if there's no round Radius
  43075. if (this._notRounded) {
  43076. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  43077. }
  43078. else {
  43079. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  43080. newPrimSize.copyFrom(primSize);
  43081. newPrimSize.width += rr * 2;
  43082. newPrimSize.height += rr * 2;
  43083. }
  43084. };
  43085. Rectangle2D.prototype.createInstanceDataParts = function () {
  43086. var res = new Array();
  43087. if (this.border) {
  43088. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43089. }
  43090. if (this.fill) {
  43091. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43092. }
  43093. return res;
  43094. };
  43095. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  43096. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43097. return false;
  43098. }
  43099. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43100. var d = part;
  43101. var size = this.actualSize;
  43102. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43103. }
  43104. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43105. var d = part;
  43106. var size = this.actualSize;
  43107. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  43108. }
  43109. return true;
  43110. };
  43111. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  43112. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  43113. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  43114. Rectangle2D.roundSubdivisions = 16;
  43115. __decorate([
  43116. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  43117. ], Rectangle2D.prototype, "actualSize", null);
  43118. __decorate([
  43119. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  43120. ], Rectangle2D.prototype, "notRounded", null);
  43121. __decorate([
  43122. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  43123. ], Rectangle2D.prototype, "roundRadius", null);
  43124. Rectangle2D = __decorate([
  43125. BABYLON.className("Rectangle2D")
  43126. ], Rectangle2D);
  43127. return Rectangle2D;
  43128. })(BABYLON.Shape2D);
  43129. BABYLON.Rectangle2D = Rectangle2D;
  43130. })(BABYLON || (BABYLON = {}));
  43131. var BABYLON;
  43132. (function (BABYLON) {
  43133. var Ellipse2DRenderCache = (function (_super) {
  43134. __extends(Ellipse2DRenderCache, _super);
  43135. function Ellipse2DRenderCache(engine, modelKey) {
  43136. _super.call(this, engine, modelKey);
  43137. this.effectsReady = false;
  43138. this.fillVB = null;
  43139. this.fillIB = null;
  43140. this.fillIndicesCount = 0;
  43141. this.instancingFillAttributes = null;
  43142. this.effectFillInstanced = null;
  43143. this.effectFill = null;
  43144. this.borderVB = null;
  43145. this.borderIB = null;
  43146. this.borderIndicesCount = 0;
  43147. this.instancingBorderAttributes = null;
  43148. this.effectBorderInstanced = null;
  43149. this.effectBorder = null;
  43150. }
  43151. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  43152. // Do nothing if the shader is still loading/preparing
  43153. if (!this.effectsReady) {
  43154. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  43155. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  43156. return false;
  43157. }
  43158. this.effectsReady = true;
  43159. }
  43160. var canvas = instanceInfo.owner.owner;
  43161. var engine = canvas.engine;
  43162. var depthFunction = 0;
  43163. if (this.effectFill && this.effectBorder) {
  43164. depthFunction = engine.getDepthFunction();
  43165. engine.setDepthFunctionToLessOrEqual();
  43166. }
  43167. var curAlphaMode = engine.getAlphaMode();
  43168. if (this.effectFill) {
  43169. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  43170. var pid = context.groupInfoPartData[partIndex];
  43171. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43172. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43173. }
  43174. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  43175. engine.enableEffect(effect);
  43176. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  43177. if (context.useInstancing) {
  43178. if (!this.instancingFillAttributes) {
  43179. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  43180. }
  43181. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43182. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43183. canvas._addDrawCallCount(1, context.renderMode);
  43184. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  43185. engine.draw(true, 0, this.fillIndicesCount, count);
  43186. engine.unbindInstanceAttributes();
  43187. }
  43188. else {
  43189. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43190. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43191. this.setupUniforms(effect, partIndex, pid._partData, i);
  43192. engine.draw(true, 0, this.fillIndicesCount);
  43193. }
  43194. }
  43195. }
  43196. if (this.effectBorder) {
  43197. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  43198. var pid = context.groupInfoPartData[partIndex];
  43199. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43200. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43201. }
  43202. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  43203. engine.enableEffect(effect);
  43204. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  43205. if (context.useInstancing) {
  43206. if (!this.instancingBorderAttributes) {
  43207. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  43208. }
  43209. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  43210. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43211. canvas._addDrawCallCount(1, context.renderMode);
  43212. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  43213. engine.draw(true, 0, this.borderIndicesCount, count);
  43214. engine.unbindInstanceAttributes();
  43215. }
  43216. else {
  43217. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43218. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43219. this.setupUniforms(effect, partIndex, pid._partData, i);
  43220. engine.draw(true, 0, this.borderIndicesCount);
  43221. }
  43222. }
  43223. }
  43224. engine.setAlphaMode(curAlphaMode);
  43225. if (this.effectFill && this.effectBorder) {
  43226. engine.setDepthFunction(depthFunction);
  43227. }
  43228. return true;
  43229. };
  43230. Ellipse2DRenderCache.prototype.dispose = function () {
  43231. if (!_super.prototype.dispose.call(this)) {
  43232. return false;
  43233. }
  43234. if (this.fillVB) {
  43235. this._engine._releaseBuffer(this.fillVB);
  43236. this.fillVB = null;
  43237. }
  43238. if (this.fillIB) {
  43239. this._engine._releaseBuffer(this.fillIB);
  43240. this.fillIB = null;
  43241. }
  43242. if (this.effectFill) {
  43243. this._engine._releaseEffect(this.effectFill);
  43244. this.effectFill = null;
  43245. }
  43246. if (this.effectFillInstanced) {
  43247. this._engine._releaseEffect(this.effectFillInstanced);
  43248. this.effectFillInstanced = null;
  43249. }
  43250. if (this.borderVB) {
  43251. this._engine._releaseBuffer(this.borderVB);
  43252. this.borderVB = null;
  43253. }
  43254. if (this.borderIB) {
  43255. this._engine._releaseBuffer(this.borderIB);
  43256. this.borderIB = null;
  43257. }
  43258. if (this.effectBorder) {
  43259. this._engine._releaseEffect(this.effectBorder);
  43260. this.effectBorder = null;
  43261. }
  43262. if (this.effectBorderInstanced) {
  43263. this._engine._releaseEffect(this.effectBorderInstanced);
  43264. this.effectBorderInstanced = null;
  43265. }
  43266. return true;
  43267. };
  43268. return Ellipse2DRenderCache;
  43269. })(BABYLON.ModelRenderCache);
  43270. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  43271. var Ellipse2DInstanceData = (function (_super) {
  43272. __extends(Ellipse2DInstanceData, _super);
  43273. function Ellipse2DInstanceData(partId) {
  43274. _super.call(this, partId, 1);
  43275. }
  43276. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  43277. get: function () {
  43278. return null;
  43279. },
  43280. enumerable: true,
  43281. configurable: true
  43282. });
  43283. __decorate([
  43284. BABYLON.instanceData()
  43285. ], Ellipse2DInstanceData.prototype, "properties", null);
  43286. return Ellipse2DInstanceData;
  43287. })(BABYLON.Shape2DInstanceData);
  43288. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  43289. var Ellipse2D = (function (_super) {
  43290. __extends(Ellipse2D, _super);
  43291. /**
  43292. * Create an Ellipse 2D Shape primitive
  43293. * @param settings a combination of settings, possible ones are
  43294. * - 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)
  43295. * - children: an array of direct children
  43296. * - id: a text identifier, for information purpose
  43297. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43298. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43299. * - scale: the initial scale of the primitive. default is 1
  43300. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43301. * - origin: define the normalized origin point location, default [0.5;0.5]
  43302. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  43303. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  43304. * - 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)
  43305. * - 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)
  43306. * - borderThickness: the thickness of the drawn border, default is 1.
  43307. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43308. * - 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!
  43309. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43310. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43311. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43312. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43313. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43314. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43315. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43316. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43317. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43318. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43319. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43320. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43321. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43322. */
  43323. function Ellipse2D(settings) {
  43324. // Avoid checking every time if the object exists
  43325. if (settings == null) {
  43326. settings = {};
  43327. }
  43328. _super.call(this, settings);
  43329. if (settings.size != null) {
  43330. this.size = settings.size;
  43331. }
  43332. else if (settings.width || settings.height) {
  43333. var size = new BABYLON.Size(settings.width, settings.height);
  43334. this.size = size;
  43335. }
  43336. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  43337. this.subdivisions = sub;
  43338. }
  43339. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  43340. get: function () {
  43341. if (this._actualSize) {
  43342. return this._actualSize;
  43343. }
  43344. return this.size;
  43345. },
  43346. set: function (value) {
  43347. this._actualSize = value;
  43348. },
  43349. enumerable: true,
  43350. configurable: true
  43351. });
  43352. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  43353. get: function () {
  43354. return this._subdivisions;
  43355. },
  43356. set: function (value) {
  43357. this._subdivisions = value;
  43358. },
  43359. enumerable: true,
  43360. configurable: true
  43361. });
  43362. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  43363. var w = this.size.width / 2;
  43364. var h = this.size.height / 2;
  43365. var x = intersectInfo._localPickPosition.x - w;
  43366. var y = intersectInfo._localPickPosition.y - h;
  43367. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  43368. };
  43369. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  43370. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  43371. };
  43372. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  43373. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  43374. return renderCache;
  43375. };
  43376. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43377. var renderCache = modelRenderCache;
  43378. var engine = this.owner.engine;
  43379. // Need to create WebGL resources for fill part?
  43380. if (this.fill) {
  43381. var vbSize = this.subdivisions + 1;
  43382. var vb = new Float32Array(vbSize);
  43383. for (var i = 0; i < vbSize; i++) {
  43384. vb[i] = i;
  43385. }
  43386. renderCache.fillVB = engine.createVertexBuffer(vb);
  43387. var triCount = vbSize - 1;
  43388. var ib = new Float32Array(triCount * 3);
  43389. for (var i = 0; i < triCount; i++) {
  43390. ib[i * 3 + 0] = 0;
  43391. ib[i * 3 + 2] = i + 1;
  43392. ib[i * 3 + 1] = i + 2;
  43393. }
  43394. ib[triCount * 3 - 2] = 1;
  43395. renderCache.fillIB = engine.createIndexBuffer(ib);
  43396. renderCache.fillIndicesCount = triCount * 3;
  43397. // 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
  43398. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], true);
  43399. if (ei) {
  43400. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43401. }
  43402. // Get the non instanced version
  43403. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], false);
  43404. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  43405. }
  43406. // Need to create WebGL resource for border part?
  43407. if (this.border) {
  43408. var vbSize = this.subdivisions * 2;
  43409. var vb = new Float32Array(vbSize);
  43410. for (var i = 0; i < vbSize; i++) {
  43411. vb[i] = i;
  43412. }
  43413. renderCache.borderVB = engine.createVertexBuffer(vb);
  43414. var triCount = vbSize;
  43415. var rs = triCount / 2;
  43416. var ib = new Float32Array(triCount * 3);
  43417. for (var i = 0; i < rs; i++) {
  43418. var r0 = i;
  43419. var r1 = (i + 1) % rs;
  43420. ib[i * 6 + 0] = rs + r1;
  43421. ib[i * 6 + 1] = rs + r0;
  43422. ib[i * 6 + 2] = r0;
  43423. ib[i * 6 + 3] = r1;
  43424. ib[i * 6 + 4] = rs + r1;
  43425. ib[i * 6 + 5] = r0;
  43426. }
  43427. renderCache.borderIB = engine.createIndexBuffer(ib);
  43428. renderCache.borderIndicesCount = (triCount * 3);
  43429. // 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
  43430. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], true);
  43431. if (ei) {
  43432. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43433. }
  43434. // Get the non instanced version
  43435. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], false);
  43436. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  43437. }
  43438. return renderCache;
  43439. };
  43440. Ellipse2D.prototype.createInstanceDataParts = function () {
  43441. var res = new Array();
  43442. if (this.border) {
  43443. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  43444. }
  43445. if (this.fill) {
  43446. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  43447. }
  43448. return res;
  43449. };
  43450. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  43451. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43452. return false;
  43453. }
  43454. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  43455. var d = part;
  43456. var size = this.actualSize;
  43457. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43458. }
  43459. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  43460. var d = part;
  43461. var size = this.actualSize;
  43462. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  43463. }
  43464. return true;
  43465. };
  43466. __decorate([
  43467. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  43468. ], Ellipse2D.prototype, "actualSize", null);
  43469. __decorate([
  43470. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  43471. ], Ellipse2D.prototype, "subdivisions", null);
  43472. Ellipse2D = __decorate([
  43473. BABYLON.className("Ellipse2D")
  43474. ], Ellipse2D);
  43475. return Ellipse2D;
  43476. })(BABYLON.Shape2D);
  43477. BABYLON.Ellipse2D = Ellipse2D;
  43478. })(BABYLON || (BABYLON = {}));
  43479. var BABYLON;
  43480. (function (BABYLON) {
  43481. var Sprite2DRenderCache = (function (_super) {
  43482. __extends(Sprite2DRenderCache, _super);
  43483. function Sprite2DRenderCache() {
  43484. _super.apply(this, arguments);
  43485. this.effectsReady = false;
  43486. this.vb = null;
  43487. this.ib = null;
  43488. this.instancingAttributes = null;
  43489. this.texture = null;
  43490. this.effect = null;
  43491. this.effectInstanced = null;
  43492. }
  43493. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  43494. // Do nothing if the shader is still loading/preparing
  43495. if (!this.effectsReady) {
  43496. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43497. return false;
  43498. }
  43499. this.effectsReady = true;
  43500. }
  43501. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  43502. var canvas = instanceInfo.owner.owner;
  43503. var engine = canvas.engine;
  43504. var cur = engine.getAlphaMode();
  43505. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43506. engine.enableEffect(effect);
  43507. effect.setTexture("diffuseSampler", this.texture);
  43508. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43509. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  43510. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43511. }
  43512. var pid = context.groupInfoPartData[0];
  43513. if (context.useInstancing) {
  43514. if (!this.instancingAttributes) {
  43515. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  43516. }
  43517. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43518. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43519. canvas._addDrawCallCount(1, context.renderMode);
  43520. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43521. engine.draw(true, 0, 6, count);
  43522. engine.unbindInstanceAttributes();
  43523. }
  43524. else {
  43525. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43526. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43527. this.setupUniforms(effect, 0, pid._partData, i);
  43528. engine.draw(true, 0, 6);
  43529. }
  43530. }
  43531. engine.setAlphaMode(cur);
  43532. return true;
  43533. };
  43534. Sprite2DRenderCache.prototype.dispose = function () {
  43535. if (!_super.prototype.dispose.call(this)) {
  43536. return false;
  43537. }
  43538. if (this.vb) {
  43539. this._engine._releaseBuffer(this.vb);
  43540. this.vb = null;
  43541. }
  43542. if (this.ib) {
  43543. this._engine._releaseBuffer(this.ib);
  43544. this.ib = null;
  43545. }
  43546. if (this.texture) {
  43547. this.texture.dispose();
  43548. this.texture = null;
  43549. }
  43550. if (this.effect) {
  43551. this._engine._releaseEffect(this.effect);
  43552. this.effect = null;
  43553. }
  43554. if (this.effectInstanced) {
  43555. this._engine._releaseEffect(this.effectInstanced);
  43556. this.effectInstanced = null;
  43557. }
  43558. return true;
  43559. };
  43560. return Sprite2DRenderCache;
  43561. })(BABYLON.ModelRenderCache);
  43562. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  43563. var Sprite2DInstanceData = (function (_super) {
  43564. __extends(Sprite2DInstanceData, _super);
  43565. function Sprite2DInstanceData(partId) {
  43566. _super.call(this, partId, 1);
  43567. }
  43568. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  43569. get: function () {
  43570. return null;
  43571. },
  43572. enumerable: true,
  43573. configurable: true
  43574. });
  43575. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  43576. get: function () {
  43577. return null;
  43578. },
  43579. enumerable: true,
  43580. configurable: true
  43581. });
  43582. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  43583. get: function () {
  43584. return null;
  43585. },
  43586. enumerable: true,
  43587. configurable: true
  43588. });
  43589. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  43590. // 3 floats being:
  43591. // - x: frame number to display
  43592. // - y: invertY setting
  43593. // - z: alignToPixel setting
  43594. get: function () {
  43595. return null;
  43596. },
  43597. enumerable: true,
  43598. configurable: true
  43599. });
  43600. __decorate([
  43601. BABYLON.instanceData()
  43602. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  43603. __decorate([
  43604. BABYLON.instanceData()
  43605. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  43606. __decorate([
  43607. BABYLON.instanceData()
  43608. ], Sprite2DInstanceData.prototype, "textureSize", null);
  43609. __decorate([
  43610. BABYLON.instanceData()
  43611. ], Sprite2DInstanceData.prototype, "properties", null);
  43612. return Sprite2DInstanceData;
  43613. })(BABYLON.InstanceDataBase);
  43614. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  43615. var Sprite2D = (function (_super) {
  43616. __extends(Sprite2D, _super);
  43617. /**
  43618. * Create an 2D Sprite primitive
  43619. * @param texture the texture that stores the sprite to render
  43620. * @param settings a combination of settings, possible ones are
  43621. * - 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)
  43622. * - children: an array of direct children
  43623. * - id a text identifier, for information purpose
  43624. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43625. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43626. * - scale: the initial scale of the primitive. default is 1
  43627. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43628. * - origin: define the normalized origin point location, default [0.5;0.5]
  43629. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  43630. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  43631. * - invertY: if true the texture Y will be inverted, default is false.
  43632. * - 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.
  43633. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  43634. * - 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!
  43635. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43636. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43637. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43638. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43639. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43640. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43641. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43642. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43643. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43644. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43645. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43646. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43647. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43648. */
  43649. function Sprite2D(texture, settings) {
  43650. var _this = this;
  43651. if (!settings) {
  43652. settings = {};
  43653. }
  43654. _super.call(this, settings);
  43655. this.texture = texture;
  43656. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43657. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43658. this.size = settings.spriteSize;
  43659. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  43660. this.spriteFrame = 0;
  43661. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  43662. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  43663. this.isAlphaTest = true;
  43664. if (settings.spriteSize == null) {
  43665. if (texture.isReady()) {
  43666. this.size = texture.getSize();
  43667. }
  43668. else {
  43669. texture.onLoadObservable.add(function () {
  43670. _this.size = texture.getSize();
  43671. _this._positioningDirty();
  43672. });
  43673. }
  43674. }
  43675. }
  43676. Object.defineProperty(Sprite2D.prototype, "texture", {
  43677. get: function () {
  43678. return this._texture;
  43679. },
  43680. set: function (value) {
  43681. this._texture = value;
  43682. },
  43683. enumerable: true,
  43684. configurable: true
  43685. });
  43686. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  43687. get: function () {
  43688. if (this._actualSize) {
  43689. return this._actualSize;
  43690. }
  43691. return this.size;
  43692. },
  43693. set: function (value) {
  43694. this._actualSize = value;
  43695. },
  43696. enumerable: true,
  43697. configurable: true
  43698. });
  43699. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  43700. get: function () {
  43701. return this._location;
  43702. },
  43703. set: function (value) {
  43704. this._location = value;
  43705. },
  43706. enumerable: true,
  43707. configurable: true
  43708. });
  43709. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  43710. get: function () {
  43711. return this._spriteFrame;
  43712. },
  43713. set: function (value) {
  43714. this._spriteFrame = value;
  43715. },
  43716. enumerable: true,
  43717. configurable: true
  43718. });
  43719. Object.defineProperty(Sprite2D.prototype, "invertY", {
  43720. get: function () {
  43721. return this._invertY;
  43722. },
  43723. set: function (value) {
  43724. this._invertY = value;
  43725. },
  43726. enumerable: true,
  43727. configurable: true
  43728. });
  43729. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  43730. /**
  43731. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  43732. */
  43733. get: function () {
  43734. return this._alignToPixel;
  43735. },
  43736. set: function (value) {
  43737. this._alignToPixel = value;
  43738. },
  43739. enumerable: true,
  43740. configurable: true
  43741. });
  43742. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  43743. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  43744. };
  43745. /**
  43746. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  43747. */
  43748. Sprite2D.prototype.getAnimatables = function () {
  43749. var res = new Array();
  43750. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  43751. res.push(this.texture);
  43752. }
  43753. return res;
  43754. };
  43755. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  43756. // 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
  43757. return true;
  43758. };
  43759. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  43760. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  43761. return sprite;
  43762. };
  43763. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  43764. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  43765. return renderCache;
  43766. };
  43767. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  43768. var renderCache = modelRenderCache;
  43769. var engine = this.owner.engine;
  43770. var vb = new Float32Array(4);
  43771. for (var i = 0; i < 4; i++) {
  43772. vb[i] = i;
  43773. }
  43774. renderCache.vb = engine.createVertexBuffer(vb);
  43775. var ib = new Float32Array(6);
  43776. ib[0] = 0;
  43777. ib[1] = 2;
  43778. ib[2] = 1;
  43779. ib[3] = 0;
  43780. ib[4] = 3;
  43781. ib[5] = 2;
  43782. renderCache.ib = engine.createIndexBuffer(ib);
  43783. renderCache.texture = this.texture;
  43784. // 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
  43785. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], true);
  43786. if (ei) {
  43787. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43788. }
  43789. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], false);
  43790. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  43791. return renderCache;
  43792. };
  43793. Sprite2D.prototype.createInstanceDataParts = function () {
  43794. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  43795. };
  43796. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  43797. Sprite2D.layoutConstructMode = true;
  43798. };
  43799. // if obj contains something, we restore the _text property
  43800. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  43801. Sprite2D.layoutConstructMode = false;
  43802. };
  43803. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  43804. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43805. return false;
  43806. }
  43807. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  43808. return false;
  43809. }
  43810. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  43811. var d = this._instanceDataParts[0];
  43812. if (Sprite2D.layoutConstructMode) {
  43813. d.topLeftUV = BABYLON.Vector2.Zero();
  43814. d.sizeUV = BABYLON.Vector2.Zero();
  43815. d.properties = BABYLON.Vector3.Zero();
  43816. d.textureSize = BABYLON.Vector2.Zero();
  43817. }
  43818. else {
  43819. var ts = this.texture.getBaseSize();
  43820. var sl = this.spriteLocation;
  43821. var ss = this.actualSize;
  43822. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  43823. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  43824. d.sizeUV = suv;
  43825. Sprite2D._prop.x = this.spriteFrame;
  43826. Sprite2D._prop.y = this.invertY ? 1 : 0;
  43827. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  43828. d.properties = Sprite2D._prop;
  43829. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  43830. }
  43831. }
  43832. return true;
  43833. };
  43834. Sprite2D.SPRITE2D_MAINPARTID = 1;
  43835. Sprite2D._prop = BABYLON.Vector3.Zero();
  43836. Sprite2D.layoutConstructMode = false;
  43837. __decorate([
  43838. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  43839. ], Sprite2D.prototype, "texture", null);
  43840. __decorate([
  43841. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  43842. ], Sprite2D.prototype, "actualSize", null);
  43843. __decorate([
  43844. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  43845. ], Sprite2D.prototype, "spriteLocation", null);
  43846. __decorate([
  43847. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  43848. ], Sprite2D.prototype, "spriteFrame", null);
  43849. __decorate([
  43850. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.invertYProperty = pi; })
  43851. ], Sprite2D.prototype, "invertY", null);
  43852. Sprite2D = __decorate([
  43853. BABYLON.className("Sprite2D")
  43854. ], Sprite2D);
  43855. return Sprite2D;
  43856. })(BABYLON.RenderablePrim2D);
  43857. BABYLON.Sprite2D = Sprite2D;
  43858. })(BABYLON || (BABYLON = {}));
  43859. var BABYLON;
  43860. (function (BABYLON) {
  43861. var Text2DRenderCache = (function (_super) {
  43862. __extends(Text2DRenderCache, _super);
  43863. function Text2DRenderCache() {
  43864. _super.apply(this, arguments);
  43865. this.effectsReady = false;
  43866. this.vb = null;
  43867. this.ib = null;
  43868. this.instancingAttributes = null;
  43869. this.fontTexture = null;
  43870. this.effect = null;
  43871. this.effectInstanced = null;
  43872. }
  43873. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  43874. // Do nothing if the shader is still loading/preparing
  43875. if (!this.effectsReady) {
  43876. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  43877. return false;
  43878. }
  43879. this.effectsReady = true;
  43880. }
  43881. var canvas = instanceInfo.owner.owner;
  43882. var engine = canvas.engine;
  43883. this.fontTexture.update();
  43884. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  43885. engine.enableEffect(effect);
  43886. effect.setTexture("diffuseSampler", this.fontTexture);
  43887. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  43888. var curAlphaMode = engine.getAlphaMode();
  43889. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  43890. var pid = context.groupInfoPartData[0];
  43891. if (context.useInstancing) {
  43892. if (!this.instancingAttributes) {
  43893. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  43894. }
  43895. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  43896. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  43897. canvas._addDrawCallCount(1, context.renderMode);
  43898. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  43899. engine.draw(true, 0, 6, count);
  43900. engine.unbindInstanceAttributes();
  43901. }
  43902. else {
  43903. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  43904. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  43905. this.setupUniforms(effect, 0, pid._partData, i);
  43906. engine.draw(true, 0, 6);
  43907. }
  43908. }
  43909. engine.setAlphaMode(curAlphaMode);
  43910. return true;
  43911. };
  43912. Text2DRenderCache.prototype.dispose = function () {
  43913. if (!_super.prototype.dispose.call(this)) {
  43914. return false;
  43915. }
  43916. if (this.vb) {
  43917. this._engine._releaseBuffer(this.vb);
  43918. this.vb = null;
  43919. }
  43920. if (this.ib) {
  43921. this._engine._releaseBuffer(this.ib);
  43922. this.ib = null;
  43923. }
  43924. if (this.fontTexture) {
  43925. this.fontTexture.dispose();
  43926. this.fontTexture = null;
  43927. }
  43928. if (this.effect) {
  43929. this._engine._releaseEffect(this.effect);
  43930. this.effect = null;
  43931. }
  43932. if (this.effectInstanced) {
  43933. this._engine._releaseEffect(this.effectInstanced);
  43934. this.effectInstanced = null;
  43935. }
  43936. return true;
  43937. };
  43938. return Text2DRenderCache;
  43939. })(BABYLON.ModelRenderCache);
  43940. BABYLON.Text2DRenderCache = Text2DRenderCache;
  43941. var Text2DInstanceData = (function (_super) {
  43942. __extends(Text2DInstanceData, _super);
  43943. function Text2DInstanceData(partId, dataElementCount) {
  43944. _super.call(this, partId, dataElementCount);
  43945. }
  43946. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  43947. get: function () {
  43948. return null;
  43949. },
  43950. enumerable: true,
  43951. configurable: true
  43952. });
  43953. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  43954. get: function () {
  43955. return null;
  43956. },
  43957. enumerable: true,
  43958. configurable: true
  43959. });
  43960. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  43961. get: function () {
  43962. return null;
  43963. },
  43964. enumerable: true,
  43965. configurable: true
  43966. });
  43967. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  43968. get: function () {
  43969. return null;
  43970. },
  43971. enumerable: true,
  43972. configurable: true
  43973. });
  43974. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  43975. get: function () {
  43976. return null;
  43977. },
  43978. enumerable: true,
  43979. configurable: true
  43980. });
  43981. __decorate([
  43982. BABYLON.instanceData()
  43983. ], Text2DInstanceData.prototype, "topLeftUV", null);
  43984. __decorate([
  43985. BABYLON.instanceData()
  43986. ], Text2DInstanceData.prototype, "sizeUV", null);
  43987. __decorate([
  43988. BABYLON.instanceData()
  43989. ], Text2DInstanceData.prototype, "textureSize", null);
  43990. __decorate([
  43991. BABYLON.instanceData()
  43992. ], Text2DInstanceData.prototype, "color", null);
  43993. __decorate([
  43994. BABYLON.instanceData()
  43995. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  43996. return Text2DInstanceData;
  43997. })(BABYLON.InstanceDataBase);
  43998. BABYLON.Text2DInstanceData = Text2DInstanceData;
  43999. var Text2D = (function (_super) {
  44000. __extends(Text2D, _super);
  44001. /**
  44002. * Create a Text primitive
  44003. * @param text the text to display
  44004. * @param settings a combination of settings, possible ones are
  44005. * - 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)
  44006. * - children: an array of direct children
  44007. * - id a text identifier, for information purpose
  44008. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44009. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44010. * - scale: the initial scale of the primitive. default is 1
  44011. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44012. * - origin: define the normalized origin point location, default [0.5;0.5]
  44013. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  44014. * - 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.
  44015. * - defaultColor: the color by default to apply on each letter of the text to display, default is plain white.
  44016. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  44017. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  44018. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  44019. * - 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!
  44020. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44021. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44022. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44023. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44024. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44025. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44026. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44027. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44028. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44029. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44030. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44031. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44032. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44033. */
  44034. function Text2D(text, settings) {
  44035. if (!settings) {
  44036. settings = {};
  44037. }
  44038. _super.call(this, settings);
  44039. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  44040. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  44041. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  44042. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  44043. this._textSize = null;
  44044. this.text = text;
  44045. this.size = (settings.size == null) ? null : settings.size;
  44046. this.isTransparent = true;
  44047. }
  44048. Object.defineProperty(Text2D.prototype, "fontName", {
  44049. get: function () {
  44050. return this._fontName;
  44051. },
  44052. set: function (value) {
  44053. if (this._fontName) {
  44054. throw new Error("Font Name change is not supported right now.");
  44055. }
  44056. this._fontName = value;
  44057. },
  44058. enumerable: true,
  44059. configurable: true
  44060. });
  44061. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  44062. get: function () {
  44063. return this._defaultFontColor;
  44064. },
  44065. set: function (value) {
  44066. this._defaultFontColor = value;
  44067. },
  44068. enumerable: true,
  44069. configurable: true
  44070. });
  44071. Object.defineProperty(Text2D.prototype, "text", {
  44072. get: function () {
  44073. return this._text;
  44074. },
  44075. set: function (value) {
  44076. this._text = value;
  44077. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  44078. this._size = null;
  44079. this._updateCharCount();
  44080. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  44081. var s = this.textSize;
  44082. },
  44083. enumerable: true,
  44084. configurable: true
  44085. });
  44086. Object.defineProperty(Text2D.prototype, "size", {
  44087. get: function () {
  44088. if (this._size != null) {
  44089. return this._size;
  44090. }
  44091. return this.textSize;
  44092. },
  44093. set: function (value) {
  44094. this._size = value;
  44095. },
  44096. enumerable: true,
  44097. configurable: true
  44098. });
  44099. Object.defineProperty(Text2D.prototype, "actualSize", {
  44100. /**
  44101. * Get the actual size of the Text2D primitive
  44102. */
  44103. get: function () {
  44104. if (this._actualSize) {
  44105. return this._actualSize;
  44106. }
  44107. return this.size;
  44108. },
  44109. enumerable: true,
  44110. configurable: true
  44111. });
  44112. Object.defineProperty(Text2D.prototype, "textSize", {
  44113. /**
  44114. * Get the area that bounds the text associated to the primitive
  44115. */
  44116. get: function () {
  44117. if (!this._textSize) {
  44118. if (this.owner) {
  44119. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  44120. if (!newSize.equals(this._textSize)) {
  44121. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  44122. this._positioningDirty();
  44123. }
  44124. this._textSize = newSize;
  44125. }
  44126. else {
  44127. return Text2D.nullSize;
  44128. }
  44129. }
  44130. return this._textSize;
  44131. },
  44132. enumerable: true,
  44133. configurable: true
  44134. });
  44135. Object.defineProperty(Text2D.prototype, "fontTexture", {
  44136. get: function () {
  44137. if (this._fontTexture) {
  44138. return this._fontTexture;
  44139. }
  44140. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44141. return this._fontTexture;
  44142. },
  44143. enumerable: true,
  44144. configurable: true
  44145. });
  44146. /**
  44147. * Dispose the primitive, remove it from its parent
  44148. */
  44149. Text2D.prototype.dispose = function () {
  44150. if (!_super.prototype.dispose.call(this)) {
  44151. return false;
  44152. }
  44153. if (this._fontTexture) {
  44154. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  44155. this._fontTexture = null;
  44156. }
  44157. return true;
  44158. };
  44159. Text2D.prototype.updateLevelBoundingInfo = function () {
  44160. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44161. };
  44162. Text2D.prototype.levelIntersect = function (intersectInfo) {
  44163. // 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...
  44164. return true;
  44165. };
  44166. Text2D.prototype.createModelRenderCache = function (modelKey) {
  44167. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  44168. return renderCache;
  44169. };
  44170. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44171. var renderCache = modelRenderCache;
  44172. var engine = this.owner.engine;
  44173. renderCache.fontTexture = this.fontTexture;
  44174. var vb = new Float32Array(4);
  44175. for (var i = 0; i < 4; i++) {
  44176. vb[i] = i;
  44177. }
  44178. renderCache.vb = engine.createVertexBuffer(vb);
  44179. var ib = new Float32Array(6);
  44180. ib[0] = 0;
  44181. ib[1] = 2;
  44182. ib[2] = 1;
  44183. ib[3] = 0;
  44184. ib[4] = 3;
  44185. ib[5] = 2;
  44186. renderCache.ib = engine.createIndexBuffer(ib);
  44187. // 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
  44188. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], true);
  44189. if (ei) {
  44190. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44191. }
  44192. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], false);
  44193. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  44194. return renderCache;
  44195. };
  44196. Text2D.prototype.createInstanceDataParts = function () {
  44197. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  44198. };
  44199. // Looks like a hack!? Yes! Because that's what it is!
  44200. // 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
  44201. // 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)
  44202. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  44203. if (!this._charCount) {
  44204. var curText = this._text;
  44205. this.text = "A";
  44206. return curText;
  44207. }
  44208. };
  44209. // if obj contains something, we restore the _text property
  44210. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  44211. if (obj !== undefined) {
  44212. this.text = obj;
  44213. }
  44214. };
  44215. Text2D.prototype.refreshInstanceDataPart = function (part) {
  44216. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44217. return false;
  44218. }
  44219. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  44220. var d = part;
  44221. var texture = this.fontTexture;
  44222. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  44223. var ts = texture.getSize();
  44224. var offset = BABYLON.Vector2.Zero();
  44225. var lh = this.fontTexture.lineHeight;
  44226. 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
  44227. var charxpos = 0;
  44228. d.dataElementCount = this._charCount;
  44229. d.curElement = 0;
  44230. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  44231. var char = _a[_i];
  44232. // Line feed
  44233. if (char === "\n") {
  44234. offset.x = 0;
  44235. offset.y -= texture.lineHeight;
  44236. }
  44237. // Tabulation ?
  44238. if (char === "\t") {
  44239. var nextPos = charxpos + this._tabulationSize;
  44240. nextPos = nextPos - (nextPos % this._tabulationSize);
  44241. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  44242. charxpos = nextPos;
  44243. continue;
  44244. }
  44245. if (char < " ") {
  44246. continue;
  44247. }
  44248. this.updateInstanceDataPart(d, offset);
  44249. var ci = texture.getChar(char);
  44250. offset.x += ci.charWidth;
  44251. d.topLeftUV = ci.topLeftUV;
  44252. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  44253. d.sizeUV = suv;
  44254. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  44255. d.color = this.defaultFontColor;
  44256. d.superSampleFactor = superSampleFactor;
  44257. ++d.curElement;
  44258. }
  44259. }
  44260. return true;
  44261. };
  44262. Text2D.prototype._updateCharCount = function () {
  44263. var count = 0;
  44264. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  44265. var char = _a[_i];
  44266. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  44267. continue;
  44268. }
  44269. ++count;
  44270. }
  44271. this._charCount = count;
  44272. };
  44273. Text2D.TEXT2D_MAINPARTID = 1;
  44274. __decorate([
  44275. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  44276. ], Text2D.prototype, "fontName", null);
  44277. __decorate([
  44278. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  44279. ], Text2D.prototype, "defaultFontColor", null);
  44280. __decorate([
  44281. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  44282. ], Text2D.prototype, "text", null);
  44283. __decorate([
  44284. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  44285. ], Text2D.prototype, "size", null);
  44286. Text2D = __decorate([
  44287. BABYLON.className("Text2D")
  44288. ], Text2D);
  44289. return Text2D;
  44290. })(BABYLON.RenderablePrim2D);
  44291. BABYLON.Text2D = Text2D;
  44292. })(BABYLON || (BABYLON = {}));
  44293. var BABYLON;
  44294. (function (BABYLON) {
  44295. var Lines2DRenderCache = (function (_super) {
  44296. __extends(Lines2DRenderCache, _super);
  44297. function Lines2DRenderCache(engine, modelKey) {
  44298. _super.call(this, engine, modelKey);
  44299. this.effectsReady = false;
  44300. this.fillVB = null;
  44301. this.fillIB = null;
  44302. this.fillIndicesCount = 0;
  44303. this.instancingFillAttributes = null;
  44304. this.effectFill = null;
  44305. this.effectFillInstanced = null;
  44306. this.borderVB = null;
  44307. this.borderIB = null;
  44308. this.borderIndicesCount = 0;
  44309. this.instancingBorderAttributes = null;
  44310. this.effectBorder = null;
  44311. this.effectBorderInstanced = null;
  44312. }
  44313. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  44314. // Do nothing if the shader is still loading/preparing
  44315. if (!this.effectsReady) {
  44316. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44317. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44318. return false;
  44319. }
  44320. this.effectsReady = true;
  44321. }
  44322. var canvas = instanceInfo.owner.owner;
  44323. var engine = canvas.engine;
  44324. var depthFunction = 0;
  44325. if (this.effectFill && this.effectBorder) {
  44326. depthFunction = engine.getDepthFunction();
  44327. engine.setDepthFunctionToLessOrEqual();
  44328. }
  44329. var curAlphaMode = engine.getAlphaMode();
  44330. if (this.effectFill) {
  44331. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44332. var pid = context.groupInfoPartData[partIndex];
  44333. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44334. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44335. }
  44336. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44337. engine.enableEffect(effect);
  44338. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  44339. if (context.useInstancing) {
  44340. if (!this.instancingFillAttributes) {
  44341. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44342. }
  44343. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44344. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44345. canvas._addDrawCallCount(1, context.renderMode);
  44346. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44347. engine.draw(true, 0, this.fillIndicesCount, count);
  44348. engine.unbindInstanceAttributes();
  44349. }
  44350. else {
  44351. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44352. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44353. this.setupUniforms(effect, partIndex, pid._partData, i);
  44354. engine.draw(true, 0, this.fillIndicesCount);
  44355. }
  44356. }
  44357. }
  44358. if (this.effectBorder) {
  44359. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44360. var pid = context.groupInfoPartData[partIndex];
  44361. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44362. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44363. }
  44364. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44365. engine.enableEffect(effect);
  44366. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  44367. if (context.useInstancing) {
  44368. if (!this.instancingBorderAttributes) {
  44369. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44370. }
  44371. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44372. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44373. canvas._addDrawCallCount(1, context.renderMode);
  44374. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44375. engine.draw(true, 0, this.borderIndicesCount, count);
  44376. engine.unbindInstanceAttributes();
  44377. }
  44378. else {
  44379. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44380. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44381. this.setupUniforms(effect, partIndex, pid._partData, i);
  44382. engine.draw(true, 0, this.borderIndicesCount);
  44383. }
  44384. }
  44385. }
  44386. engine.setAlphaMode(curAlphaMode);
  44387. if (this.effectFill && this.effectBorder) {
  44388. engine.setDepthFunction(depthFunction);
  44389. }
  44390. return true;
  44391. };
  44392. Lines2DRenderCache.prototype.dispose = function () {
  44393. if (!_super.prototype.dispose.call(this)) {
  44394. return false;
  44395. }
  44396. if (this.fillVB) {
  44397. this._engine._releaseBuffer(this.fillVB);
  44398. this.fillVB = null;
  44399. }
  44400. if (this.fillIB) {
  44401. this._engine._releaseBuffer(this.fillIB);
  44402. this.fillIB = null;
  44403. }
  44404. if (this.effectFill) {
  44405. this._engine._releaseEffect(this.effectFill);
  44406. this.effectFill = null;
  44407. }
  44408. if (this.effectFillInstanced) {
  44409. this._engine._releaseEffect(this.effectFillInstanced);
  44410. this.effectFillInstanced = null;
  44411. }
  44412. if (this.borderVB) {
  44413. this._engine._releaseBuffer(this.borderVB);
  44414. this.borderVB = null;
  44415. }
  44416. if (this.borderIB) {
  44417. this._engine._releaseBuffer(this.borderIB);
  44418. this.borderIB = null;
  44419. }
  44420. if (this.effectBorder) {
  44421. this._engine._releaseEffect(this.effectBorder);
  44422. this.effectBorder = null;
  44423. }
  44424. if (this.effectBorderInstanced) {
  44425. this._engine._releaseEffect(this.effectBorderInstanced);
  44426. this.effectBorderInstanced = null;
  44427. }
  44428. return true;
  44429. };
  44430. return Lines2DRenderCache;
  44431. })(BABYLON.ModelRenderCache);
  44432. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  44433. var Lines2DInstanceData = (function (_super) {
  44434. __extends(Lines2DInstanceData, _super);
  44435. function Lines2DInstanceData(partId) {
  44436. _super.call(this, partId, 1);
  44437. }
  44438. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  44439. get: function () {
  44440. return null;
  44441. },
  44442. enumerable: true,
  44443. configurable: true
  44444. });
  44445. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  44446. get: function () {
  44447. return null;
  44448. },
  44449. enumerable: true,
  44450. configurable: true
  44451. });
  44452. __decorate([
  44453. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44454. ], Lines2DInstanceData.prototype, "boundingMin", null);
  44455. __decorate([
  44456. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  44457. ], Lines2DInstanceData.prototype, "boundingMax", null);
  44458. return Lines2DInstanceData;
  44459. })(BABYLON.Shape2DInstanceData);
  44460. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  44461. var Lines2D = (function (_super) {
  44462. __extends(Lines2D, _super);
  44463. /**
  44464. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  44465. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  44466. * @param settings a combination of settings, possible ones are
  44467. * - 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)
  44468. * - children: an array of direct children
  44469. * - id a text identifier, for information purpose
  44470. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44471. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44472. * - scale: the initial scale of the primitive. default is 1
  44473. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44474. * - origin: define the normalized origin point location, default [0.5;0.5]
  44475. * - 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.
  44476. * - 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.
  44477. * - 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.
  44478. * - 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.
  44479. * - 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)
  44480. * - 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)
  44481. * - borderThickness: the thickness of the drawn border, default is 1.
  44482. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44483. * - 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!
  44484. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44485. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44486. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44487. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44488. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44489. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44490. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44491. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44492. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44493. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44494. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44495. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44496. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44497. */
  44498. function Lines2D(points, settings) {
  44499. if (!settings) {
  44500. settings = {};
  44501. }
  44502. _super.call(this, settings);
  44503. this._fillVB = null;
  44504. this._fillIB = null;
  44505. this._borderVB = null;
  44506. this._borderIB = null;
  44507. this._size = BABYLON.Size.Zero();
  44508. this._boundingMin = null;
  44509. this._boundingMax = null;
  44510. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  44511. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  44512. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  44513. var closed = (settings.closed == null) ? false : settings.closed;
  44514. this.points = points;
  44515. this.fillThickness = fillThickness;
  44516. this.startCap = startCap;
  44517. this.endCap = endCap;
  44518. this.closed = closed;
  44519. }
  44520. Object.defineProperty(Lines2D, "NoCap", {
  44521. /**
  44522. * No Cap to apply on the extremity
  44523. */
  44524. get: function () { return Lines2D._noCap; },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. Object.defineProperty(Lines2D, "RoundCap", {
  44529. /**
  44530. * A round cap, will use the line thickness as diameter
  44531. */
  44532. get: function () { return Lines2D._roundCap; },
  44533. enumerable: true,
  44534. configurable: true
  44535. });
  44536. Object.defineProperty(Lines2D, "TriangleCap", {
  44537. /**
  44538. * Creates a triangle at the extremity.
  44539. */
  44540. get: function () { return Lines2D._triangleCap; },
  44541. enumerable: true,
  44542. configurable: true
  44543. });
  44544. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  44545. /**
  44546. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  44547. */
  44548. get: function () { return Lines2D._squareAnchorCap; },
  44549. enumerable: true,
  44550. configurable: true
  44551. });
  44552. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  44553. /**
  44554. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  44555. */
  44556. get: function () { return Lines2D._roundAnchorCap; },
  44557. enumerable: true,
  44558. configurable: true
  44559. });
  44560. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  44561. /**
  44562. * Creates a diamond anchor at the extremity.
  44563. */
  44564. get: function () { return Lines2D._diamondAnchorCap; },
  44565. enumerable: true,
  44566. configurable: true
  44567. });
  44568. Object.defineProperty(Lines2D, "ArrowCap", {
  44569. /**
  44570. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  44571. */
  44572. get: function () { return Lines2D._arrowCap; },
  44573. enumerable: true,
  44574. configurable: true
  44575. });
  44576. Object.defineProperty(Lines2D.prototype, "points", {
  44577. get: function () {
  44578. return this._points;
  44579. },
  44580. set: function (value) {
  44581. this._points = value;
  44582. this._boundingBoxDirty();
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  44588. get: function () {
  44589. return this._fillThickness;
  44590. },
  44591. set: function (value) {
  44592. this._fillThickness = value;
  44593. },
  44594. enumerable: true,
  44595. configurable: true
  44596. });
  44597. Object.defineProperty(Lines2D.prototype, "closed", {
  44598. get: function () {
  44599. return this._closed;
  44600. },
  44601. set: function (value) {
  44602. this._closed = value;
  44603. },
  44604. enumerable: true,
  44605. configurable: true
  44606. });
  44607. Object.defineProperty(Lines2D.prototype, "startCap", {
  44608. get: function () {
  44609. return this._startCap;
  44610. },
  44611. set: function (value) {
  44612. this._startCap = value;
  44613. },
  44614. enumerable: true,
  44615. configurable: true
  44616. });
  44617. Object.defineProperty(Lines2D.prototype, "endCap", {
  44618. get: function () {
  44619. return this._endCap;
  44620. },
  44621. set: function (value) {
  44622. this._endCap = value;
  44623. },
  44624. enumerable: true,
  44625. configurable: true
  44626. });
  44627. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  44628. var _this = this;
  44629. if (this._contour == null) {
  44630. this._computeLines2D();
  44631. }
  44632. var pl = this.points.length;
  44633. var l = this.closed ? pl + 1 : pl;
  44634. var p = intersectInfo._localPickPosition;
  44635. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  44636. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  44637. for (var i = 1; i < l; i++) {
  44638. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  44639. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  44640. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  44641. return true;
  44642. }
  44643. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  44644. return true;
  44645. }
  44646. Lines2D._prevA.x = Lines2D._curA.x;
  44647. Lines2D._prevA.y = Lines2D._curA.y;
  44648. Lines2D._prevB.x = Lines2D._curB.x;
  44649. Lines2D._prevB.y = Lines2D._curB.y;
  44650. }
  44651. var capIntersect = function (tri, points) {
  44652. var l = tri.length;
  44653. for (var i = 0; i < l; i += 3) {
  44654. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  44655. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  44656. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  44657. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  44658. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  44659. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  44660. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  44661. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  44662. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  44663. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  44664. return true;
  44665. }
  44666. }
  44667. return false;
  44668. };
  44669. if (this._startCapTriIndices) {
  44670. if (capIntersect(this._startCapTriIndices, this._startCapContour)) {
  44671. return true;
  44672. }
  44673. if (capIntersect(this._endCapTriIndices, this._endCapContour)) {
  44674. return true;
  44675. }
  44676. }
  44677. return false;
  44678. };
  44679. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  44680. get: function () {
  44681. if (!this._boundingMin) {
  44682. this._computeLines2D();
  44683. }
  44684. return this._boundingMin;
  44685. },
  44686. enumerable: true,
  44687. configurable: true
  44688. });
  44689. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  44690. get: function () {
  44691. if (!this._boundingMax) {
  44692. this._computeLines2D();
  44693. }
  44694. return this._boundingMax;
  44695. },
  44696. enumerable: true,
  44697. configurable: true
  44698. });
  44699. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  44700. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  44701. // Remove the BORDER category, we don't use it in the VertexShader
  44702. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  44703. if (i !== -1) {
  44704. res.splice(i, 1);
  44705. }
  44706. return res;
  44707. };
  44708. Lines2D.prototype.updateLevelBoundingInfo = function () {
  44709. if (!this._boundingMin) {
  44710. this._computeLines2D();
  44711. }
  44712. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  44713. };
  44714. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  44715. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  44716. return renderCache;
  44717. };
  44718. ///////////////////////////////////////////////////////////////////////////////////
  44719. // Methods for Lines building
  44720. Lines2D.prototype._perp = function (v, res) {
  44721. res.x = v.y;
  44722. res.y = -v.x;
  44723. };
  44724. ;
  44725. Lines2D.prototype._direction = function (a, b, res) {
  44726. a.subtractToRef(b, res);
  44727. res.normalize();
  44728. };
  44729. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  44730. a.addToRef(b, tangent);
  44731. tangent.normalize();
  44732. miter.x = -tangent.y;
  44733. miter.y = tangent.x;
  44734. Lines2D._miterTps.x = -a.y;
  44735. Lines2D._miterTps.y = a.x;
  44736. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  44737. };
  44738. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  44739. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  44740. if (d === 0)
  44741. return false;
  44742. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  44743. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  44744. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  44745. return false;
  44746. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  44747. return false;
  44748. return true;
  44749. };
  44750. Lines2D.prototype._updateMinMax = function (array, offset) {
  44751. if (offset >= array.length) {
  44752. return;
  44753. }
  44754. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  44755. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  44756. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  44757. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  44758. };
  44759. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  44760. var borderMode = borderThickness != null && !isNaN(borderThickness);
  44761. var off = index * (borderMode ? 8 : 4);
  44762. // 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)
  44763. if (off >= array.length) {
  44764. return;
  44765. }
  44766. // Store start/end normal, we need it for the cap construction
  44767. if (index === 0) {
  44768. this._perp(n, Lines2D._startDir);
  44769. }
  44770. else if (index === max - 1) {
  44771. this._perp(n, Lines2D._endDir);
  44772. Lines2D._endDir.x *= -1;
  44773. Lines2D._endDir.y *= -1;
  44774. }
  44775. var swap = false;
  44776. array[off + 0] = p.x + n.x * halfThickness;
  44777. array[off + 1] = p.y + n.y * halfThickness;
  44778. array[off + 2] = p.x + n.x * -halfThickness;
  44779. array[off + 3] = p.y + n.y * -halfThickness;
  44780. this._updateMinMax(array, off);
  44781. this._updateMinMax(array, off + 2);
  44782. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  44783. // 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
  44784. if (detectFlip !== undefined) {
  44785. // Flip if intersect
  44786. var flipOff = detectFlip * (borderMode ? 8 : 4);
  44787. 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])) {
  44788. swap = true;
  44789. var tps = array[off + 0];
  44790. array[off + 0] = array[off + 2];
  44791. array[off + 2] = tps;
  44792. tps = array[off + 1];
  44793. array[off + 1] = array[off + 3];
  44794. array[off + 3] = tps;
  44795. }
  44796. }
  44797. if (borderMode) {
  44798. var t = halfThickness + borderThickness;
  44799. array[off + 4] = p.x + n.x * (swap ? -t : t);
  44800. array[off + 5] = p.y + n.y * (swap ? -t : t);
  44801. array[off + 6] = p.x + n.x * (swap ? t : -t);
  44802. array[off + 7] = p.y + n.y * (swap ? t : -t);
  44803. this._updateMinMax(array, off + 4);
  44804. this._updateMinMax(array, off + 6);
  44805. }
  44806. if (contour) {
  44807. off += borderMode ? 4 : 0;
  44808. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  44809. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  44810. }
  44811. };
  44812. Lines2D.prototype._getCapSize = function (type, border) {
  44813. if (border === void 0) { border = false; }
  44814. var sd = Lines2D._roundCapSubDiv;
  44815. // If no array given, we call this to get the size
  44816. var vbsize = 0, ibsize = 0;
  44817. switch (type) {
  44818. case Lines2D.NoCap:
  44819. {
  44820. // If the line is not close and we're computing border, we add the size to generate the edge border
  44821. if (!this.closed && border) {
  44822. vbsize = 4;
  44823. ibsize = 6;
  44824. }
  44825. else {
  44826. vbsize = ibsize = 0;
  44827. }
  44828. break;
  44829. }
  44830. case Lines2D.RoundCap:
  44831. {
  44832. if (border) {
  44833. vbsize = sd;
  44834. ibsize = (sd - 2) * 3;
  44835. }
  44836. else {
  44837. vbsize = (sd / 2) + 1;
  44838. ibsize = (sd / 2) * 3;
  44839. }
  44840. break;
  44841. }
  44842. case Lines2D.ArrowCap:
  44843. {
  44844. if (border) {
  44845. vbsize = 12;
  44846. ibsize = 24;
  44847. }
  44848. else {
  44849. vbsize = 3;
  44850. ibsize = 3;
  44851. }
  44852. break;
  44853. }
  44854. case Lines2D.TriangleCap:
  44855. {
  44856. if (border) {
  44857. vbsize = 6;
  44858. ibsize = 12;
  44859. }
  44860. else {
  44861. vbsize = 3;
  44862. ibsize = 3;
  44863. }
  44864. break;
  44865. }
  44866. case Lines2D.DiamondAnchorCap:
  44867. {
  44868. if (border) {
  44869. vbsize = 10;
  44870. ibsize = 24;
  44871. }
  44872. else {
  44873. vbsize = 5;
  44874. ibsize = 9;
  44875. }
  44876. break;
  44877. }
  44878. case Lines2D.SquareAnchorCap:
  44879. {
  44880. if (border) {
  44881. vbsize = 12;
  44882. ibsize = 30;
  44883. }
  44884. else {
  44885. vbsize = 4;
  44886. ibsize = 6;
  44887. }
  44888. break;
  44889. }
  44890. case Lines2D.RoundAnchorCap:
  44891. {
  44892. if (border) {
  44893. vbsize = sd * 2;
  44894. ibsize = (sd - 1) * 6;
  44895. }
  44896. else {
  44897. vbsize = sd + 1;
  44898. ibsize = (sd + 1) * 3;
  44899. }
  44900. break;
  44901. }
  44902. }
  44903. return { vbsize: vbsize * 2, ibsize: ibsize };
  44904. };
  44905. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  44906. var c = Math.cos(rotation);
  44907. var s = Math.sin(rotation);
  44908. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  44909. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  44910. var offset = baseOffset + (index * 2);
  44911. vb[offset + 0] = Lines2D._tpsV.x;
  44912. vb[offset + 1] = Lines2D._tpsV.y;
  44913. if (contour) {
  44914. contour.push(Lines2D._tpsV.x);
  44915. contour.push(Lines2D._tpsV.y);
  44916. }
  44917. this._updateMinMax(vb, offset);
  44918. return (baseOffset + index * 2) / 2;
  44919. };
  44920. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  44921. ib[baseOffset + index] = vertexIndex;
  44922. };
  44923. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  44924. // 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
  44925. var sd = Lines2D._roundCapSubDiv;
  44926. var dir = new BABYLON.Vector2(1, 0);
  44927. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  44928. var ht = thickness / 2;
  44929. var t = thickness;
  44930. var borderMode = borderThickness != null;
  44931. var bt = borderThickness;
  44932. switch (type) {
  44933. case Lines2D.NoCap:
  44934. if (borderMode && !this.closed) {
  44935. var vi = 0;
  44936. var ii = 0;
  44937. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  44938. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  44939. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  44940. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  44941. this._storeIndex(ib, ibi, ii++, v1);
  44942. this._storeIndex(ib, ibi, ii++, v2);
  44943. this._storeIndex(ib, ibi, ii++, v3);
  44944. this._storeIndex(ib, ibi, ii++, v1);
  44945. this._storeIndex(ib, ibi, ii++, v3);
  44946. this._storeIndex(ib, ibi, ii++, v4);
  44947. }
  44948. break;
  44949. case Lines2D.ArrowCap:
  44950. ht *= 2;
  44951. case Lines2D.TriangleCap:
  44952. {
  44953. if (borderMode) {
  44954. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  44955. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  44956. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  44957. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  44958. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  44959. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  44960. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  44961. var ii = 0;
  44962. this._storeIndex(ib, ibi, ii++, v1);
  44963. this._storeIndex(ib, ibi, ii++, v4);
  44964. this._storeIndex(ib, ibi, ii++, v5);
  44965. this._storeIndex(ib, ibi, ii++, v1);
  44966. this._storeIndex(ib, ibi, ii++, v5);
  44967. this._storeIndex(ib, ibi, ii++, v2);
  44968. this._storeIndex(ib, ibi, ii++, v6);
  44969. this._storeIndex(ib, ibi, ii++, v3);
  44970. this._storeIndex(ib, ibi, ii++, v2);
  44971. this._storeIndex(ib, ibi, ii++, v6);
  44972. this._storeIndex(ib, ibi, ii++, v2);
  44973. this._storeIndex(ib, ibi, ii++, v5);
  44974. if (type === Lines2D.ArrowCap) {
  44975. var rht = thickness / 2;
  44976. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  44977. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  44978. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  44979. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  44980. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  44981. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  44982. this._storeIndex(ib, ibi, ii++, v7);
  44983. this._storeIndex(ib, ibi, ii++, v8);
  44984. this._storeIndex(ib, ibi, ii++, v9);
  44985. this._storeIndex(ib, ibi, ii++, v7);
  44986. this._storeIndex(ib, ibi, ii++, v9);
  44987. this._storeIndex(ib, ibi, ii++, v4);
  44988. this._storeIndex(ib, ibi, ii++, v10);
  44989. this._storeIndex(ib, ibi, ii++, v12);
  44990. this._storeIndex(ib, ibi, ii++, v11);
  44991. this._storeIndex(ib, ibi, ii++, v10);
  44992. this._storeIndex(ib, ibi, ii++, v6);
  44993. this._storeIndex(ib, ibi, ii++, v12);
  44994. }
  44995. }
  44996. else {
  44997. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  44998. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  44999. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  45000. this._storeIndex(ib, ibi, 0, v1);
  45001. this._storeIndex(ib, ibi, 1, v2);
  45002. this._storeIndex(ib, ibi, 2, v3);
  45003. }
  45004. break;
  45005. }
  45006. case Lines2D.RoundCap:
  45007. {
  45008. if (borderMode) {
  45009. var curA = -Math.PI / 2;
  45010. var incA = Math.PI / (sd / 2 - 1);
  45011. var ii = 0;
  45012. for (var i = 0; i < (sd / 2); i++) {
  45013. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  45014. 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);
  45015. if (i > 0) {
  45016. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45017. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45018. this._storeIndex(ib, ibi, ii++, v2);
  45019. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45020. this._storeIndex(ib, ibi, ii++, v2);
  45021. this._storeIndex(ib, ibi, ii++, v1);
  45022. }
  45023. curA += incA;
  45024. }
  45025. }
  45026. else {
  45027. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  45028. var curA = -Math.PI / 2;
  45029. var incA = Math.PI / (sd / 2 - 1);
  45030. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  45031. curA += incA;
  45032. for (var i = 1; i < (sd / 2); i++) {
  45033. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  45034. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45035. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45036. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45037. curA += incA;
  45038. }
  45039. }
  45040. break;
  45041. }
  45042. case Lines2D.SquareAnchorCap:
  45043. {
  45044. var vi = 0;
  45045. var c = borderMode ? null : contour;
  45046. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  45047. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  45048. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  45049. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  45050. if (borderMode) {
  45051. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  45052. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  45053. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  45054. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  45055. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  45056. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  45057. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  45058. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  45059. var ii = 0;
  45060. this._storeIndex(ib, ibi, ii++, v6);
  45061. this._storeIndex(ib, ibi, ii++, v1);
  45062. this._storeIndex(ib, ibi, ii++, v5);
  45063. this._storeIndex(ib, ibi, ii++, v6);
  45064. this._storeIndex(ib, ibi, ii++, v7);
  45065. this._storeIndex(ib, ibi, ii++, v1);
  45066. this._storeIndex(ib, ibi, ii++, v1);
  45067. this._storeIndex(ib, ibi, ii++, v7);
  45068. this._storeIndex(ib, ibi, ii++, v8);
  45069. this._storeIndex(ib, ibi, ii++, v1);
  45070. this._storeIndex(ib, ibi, ii++, v8);
  45071. this._storeIndex(ib, ibi, ii++, v2);
  45072. this._storeIndex(ib, ibi, ii++, v2);
  45073. this._storeIndex(ib, ibi, ii++, v8);
  45074. this._storeIndex(ib, ibi, ii++, v9);
  45075. this._storeIndex(ib, ibi, ii++, v2);
  45076. this._storeIndex(ib, ibi, ii++, v9);
  45077. this._storeIndex(ib, ibi, ii++, v3);
  45078. this._storeIndex(ib, ibi, ii++, v3);
  45079. this._storeIndex(ib, ibi, ii++, v9);
  45080. this._storeIndex(ib, ibi, ii++, v10);
  45081. this._storeIndex(ib, ibi, ii++, v3);
  45082. this._storeIndex(ib, ibi, ii++, v10);
  45083. this._storeIndex(ib, ibi, ii++, v4);
  45084. this._storeIndex(ib, ibi, ii++, v10);
  45085. this._storeIndex(ib, ibi, ii++, v11);
  45086. this._storeIndex(ib, ibi, ii++, v4);
  45087. this._storeIndex(ib, ibi, ii++, v11);
  45088. this._storeIndex(ib, ibi, ii++, v12);
  45089. this._storeIndex(ib, ibi, ii++, v4);
  45090. }
  45091. else {
  45092. this._storeIndex(ib, ibi, 0, v1);
  45093. this._storeIndex(ib, ibi, 1, v2);
  45094. this._storeIndex(ib, ibi, 2, v3);
  45095. this._storeIndex(ib, ibi, 3, v1);
  45096. this._storeIndex(ib, ibi, 4, v3);
  45097. this._storeIndex(ib, ibi, 5, v4);
  45098. }
  45099. break;
  45100. }
  45101. case Lines2D.RoundAnchorCap:
  45102. {
  45103. var cpos = Math.sqrt(t * t - ht * ht);
  45104. var center = new BABYLON.Vector2(cpos, 0);
  45105. var curA = BABYLON.Tools.ToRadians(-150);
  45106. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  45107. if (borderMode) {
  45108. var ii = 0;
  45109. for (var i = 0; i < sd; i++) {
  45110. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45111. 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);
  45112. if (i > 0) {
  45113. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45114. this._storeIndex(ib, ibi, ii++, v2 - 2);
  45115. this._storeIndex(ib, ibi, ii++, v2);
  45116. this._storeIndex(ib, ibi, ii++, v1 - 2);
  45117. this._storeIndex(ib, ibi, ii++, v2);
  45118. this._storeIndex(ib, ibi, ii++, v1);
  45119. }
  45120. curA += incA;
  45121. }
  45122. }
  45123. else {
  45124. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  45125. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  45126. curA += incA;
  45127. for (var i = 1; i < sd; i++) {
  45128. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  45129. this._storeIndex(ib, ibi, i * 3 + 0, c);
  45130. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  45131. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  45132. curA += incA;
  45133. }
  45134. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  45135. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  45136. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  45137. }
  45138. break;
  45139. }
  45140. case Lines2D.DiamondAnchorCap:
  45141. {
  45142. var vi = 0;
  45143. var c = borderMode ? null : contour;
  45144. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  45145. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  45146. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  45147. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  45148. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  45149. if (borderMode) {
  45150. var f = Math.sqrt(bt * bt * 2);
  45151. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  45152. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  45153. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  45154. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  45155. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  45156. var ii = 0;
  45157. this._storeIndex(ib, ibi, ii++, v6);
  45158. this._storeIndex(ib, ibi, ii++, v7);
  45159. this._storeIndex(ib, ibi, ii++, v1);
  45160. this._storeIndex(ib, ibi, ii++, v1);
  45161. this._storeIndex(ib, ibi, ii++, v7);
  45162. this._storeIndex(ib, ibi, ii++, v2);
  45163. this._storeIndex(ib, ibi, ii++, v2);
  45164. this._storeIndex(ib, ibi, ii++, v7);
  45165. this._storeIndex(ib, ibi, ii++, v8);
  45166. this._storeIndex(ib, ibi, ii++, v2);
  45167. this._storeIndex(ib, ibi, ii++, v8);
  45168. this._storeIndex(ib, ibi, ii++, v3);
  45169. this._storeIndex(ib, ibi, ii++, v3);
  45170. this._storeIndex(ib, ibi, ii++, v8);
  45171. this._storeIndex(ib, ibi, ii++, v9);
  45172. this._storeIndex(ib, ibi, ii++, v3);
  45173. this._storeIndex(ib, ibi, ii++, v9);
  45174. this._storeIndex(ib, ibi, ii++, v4);
  45175. this._storeIndex(ib, ibi, ii++, v4);
  45176. this._storeIndex(ib, ibi, ii++, v9);
  45177. this._storeIndex(ib, ibi, ii++, v10);
  45178. this._storeIndex(ib, ibi, ii++, v4);
  45179. this._storeIndex(ib, ibi, ii++, v10);
  45180. this._storeIndex(ib, ibi, ii++, v5);
  45181. }
  45182. else {
  45183. this._storeIndex(ib, ibi, 0, v1);
  45184. this._storeIndex(ib, ibi, 1, v2);
  45185. this._storeIndex(ib, ibi, 2, v3);
  45186. this._storeIndex(ib, ibi, 3, v1);
  45187. this._storeIndex(ib, ibi, 4, v3);
  45188. this._storeIndex(ib, ibi, 5, v5);
  45189. this._storeIndex(ib, ibi, 6, v5);
  45190. this._storeIndex(ib, ibi, 7, v3);
  45191. this._storeIndex(ib, ibi, 8, v4);
  45192. }
  45193. break;
  45194. }
  45195. }
  45196. return null;
  45197. };
  45198. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  45199. var lineA = BABYLON.Vector2.Zero();
  45200. var lineB = BABYLON.Vector2.Zero();
  45201. var tangent = BABYLON.Vector2.Zero();
  45202. var miter = BABYLON.Vector2.Zero();
  45203. var curNormal = null;
  45204. if (this.closed) {
  45205. this.points.push(this.points[0]);
  45206. }
  45207. var total = this.points.length;
  45208. for (var i = 1; i < total; i++) {
  45209. var last = this.points[i - 1];
  45210. var cur = this.points[i];
  45211. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  45212. this._direction(cur, last, lineA);
  45213. if (!curNormal) {
  45214. curNormal = BABYLON.Vector2.Zero();
  45215. this._perp(lineA, curNormal);
  45216. }
  45217. if (i === 1) {
  45218. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  45219. }
  45220. if (!next) {
  45221. this._perp(lineA, curNormal);
  45222. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  45223. }
  45224. else {
  45225. this._direction(next, cur, lineB);
  45226. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  45227. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  45228. }
  45229. }
  45230. if (this.points.length > 2 && this.closed) {
  45231. var last2 = this.points[total - 2];
  45232. var cur2 = this.points[0];
  45233. var next2 = this.points[1];
  45234. this._direction(cur2, last2, lineA);
  45235. this._direction(next2, cur2, lineB);
  45236. this._perp(lineA, curNormal);
  45237. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  45238. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  45239. // Patch contour
  45240. if (contour) {
  45241. var off = (bt == null) ? 0 : 4;
  45242. contour[0].x = vb[off + 0];
  45243. contour[0].y = vb[off + 1];
  45244. contour[1].x = vb[off + 2];
  45245. contour[1].y = vb[off + 3];
  45246. }
  45247. }
  45248. // Remove the point we added at the beginning
  45249. if (this.closed) {
  45250. this.points.splice(total - 1);
  45251. }
  45252. };
  45253. // Methods for Lines building
  45254. ///////////////////////////////////////////////////////////////////////////////////
  45255. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45256. var renderCache = modelRenderCache;
  45257. var engine = this.owner.engine;
  45258. if (this._fillVB === null) {
  45259. this._computeLines2D();
  45260. }
  45261. // Need to create WebGL resources for fill part?
  45262. if (this.fill) {
  45263. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  45264. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  45265. renderCache.fillIndicesCount = this._fillIB.length;
  45266. // 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
  45267. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], true);
  45268. if (ei) {
  45269. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45270. }
  45271. // Get the non instanced version
  45272. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], false);
  45273. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  45274. }
  45275. // Need to create WebGL resources for border part?
  45276. if (this.border) {
  45277. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  45278. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  45279. renderCache.borderIndicesCount = this._borderIB.length;
  45280. // 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
  45281. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], true);
  45282. if (ei) {
  45283. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45284. }
  45285. // Get the non instanced version
  45286. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], false);
  45287. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  45288. }
  45289. this._fillVB = null;
  45290. this._fillIB = null;
  45291. this._borderVB = null;
  45292. this._borderIB = null;
  45293. return renderCache;
  45294. };
  45295. Lines2D.prototype._computeLines2D = function () {
  45296. // Init min/max because their being computed here
  45297. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  45298. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  45299. var contour = new Array();
  45300. var startCapContour = new Array();
  45301. var endCapContour = new Array();
  45302. // Need to create WebGL resources for fill part?
  45303. if (this.fill) {
  45304. var startCapInfo = this._getCapSize(this.startCap);
  45305. var endCapInfo = this._getCapSize(this.endCap);
  45306. var count = this.points.length;
  45307. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45308. this._fillVB = new Float32Array(vbSize);
  45309. var vb = this._fillVB;
  45310. var ht = this.fillThickness / 2;
  45311. var total = this.points.length;
  45312. this._buildLine(vb, this.border ? null : contour, ht);
  45313. var max = total * 2;
  45314. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  45315. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45316. var ib = this._fillIB;
  45317. for (var i = 0; i < triCount; i += 2) {
  45318. ib[i * 3 + 0] = i + 0;
  45319. ib[i * 3 + 1] = i + 1;
  45320. ib[i * 3 + 2] = (i + 2) % max;
  45321. ib[i * 3 + 3] = i + 1;
  45322. ib[i * 3 + 4] = (i + 3) % max;
  45323. ib[i * 3 + 5] = (i + 2) % max;
  45324. }
  45325. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  45326. 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);
  45327. }
  45328. // Need to create WebGL resources for border part?
  45329. if (this.border) {
  45330. var startCapInfo = this._getCapSize(this.startCap, true);
  45331. var endCapInfo = this._getCapSize(this.endCap, true);
  45332. var count = this.points.length;
  45333. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  45334. this._borderVB = new Float32Array(vbSize);
  45335. var vb = this._borderVB;
  45336. var ht = this.fillThickness / 2;
  45337. var bt = this.borderThickness;
  45338. var total = this.points.length;
  45339. this._buildLine(vb, contour, ht, bt);
  45340. var max = total * 2 * 2;
  45341. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  45342. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  45343. var ib = this._borderIB;
  45344. for (var i = 0; i < triCount; i += 4) {
  45345. ib[i * 3 + 0] = i + 0;
  45346. ib[i * 3 + 1] = i + 2;
  45347. ib[i * 3 + 2] = (i + 6) % max;
  45348. ib[i * 3 + 3] = i + 0;
  45349. ib[i * 3 + 4] = (i + 6) % max;
  45350. ib[i * 3 + 5] = (i + 4) % max;
  45351. ib[i * 3 + 6] = i + 3;
  45352. ib[i * 3 + 7] = i + 1;
  45353. ib[i * 3 + 8] = (i + 5) % max;
  45354. ib[i * 3 + 9] = i + 3;
  45355. ib[i * 3 + 10] = (i + 5) % max;
  45356. ib[i * 3 + 11] = (i + 7) % max;
  45357. }
  45358. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  45359. 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);
  45360. }
  45361. this._contour = contour;
  45362. if (startCapContour.length > 0) {
  45363. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  45364. this._startCapTriIndices = startCapTri;
  45365. this._startCapContour = startCapContour;
  45366. }
  45367. if (endCapContour.length > 0) {
  45368. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  45369. this._endCapContour = endCapContour;
  45370. this._endCapTriIndices = endCapTri;
  45371. }
  45372. var bs = this._boundingMax.subtract(this._boundingMin);
  45373. this._size.width = bs.x;
  45374. this._size.height = bs.y;
  45375. };
  45376. Object.defineProperty(Lines2D.prototype, "size", {
  45377. get: function () {
  45378. if (this._size == null) {
  45379. this._computeLines2D();
  45380. }
  45381. return this._size;
  45382. },
  45383. enumerable: true,
  45384. configurable: true
  45385. });
  45386. Lines2D.prototype.createInstanceDataParts = function () {
  45387. var res = new Array();
  45388. if (this.border) {
  45389. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  45390. }
  45391. if (this.fill) {
  45392. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  45393. }
  45394. return res;
  45395. };
  45396. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  45397. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45398. return false;
  45399. }
  45400. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  45401. var d = part;
  45402. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  45403. d.boundingMin = this.boundingMin;
  45404. d.boundingMax = this.boundingMax;
  45405. }
  45406. }
  45407. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  45408. var d = part;
  45409. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  45410. d.boundingMin = this.boundingMin;
  45411. d.boundingMax = this.boundingMax;
  45412. }
  45413. }
  45414. return true;
  45415. };
  45416. Lines2D._prevA = BABYLON.Vector2.Zero();
  45417. Lines2D._prevB = BABYLON.Vector2.Zero();
  45418. Lines2D._curA = BABYLON.Vector2.Zero();
  45419. Lines2D._curB = BABYLON.Vector2.Zero();
  45420. Lines2D._miterTps = BABYLON.Vector2.Zero();
  45421. Lines2D._startDir = BABYLON.Vector2.Zero();
  45422. Lines2D._endDir = BABYLON.Vector2.Zero();
  45423. Lines2D._tpsV = BABYLON.Vector2.Zero();
  45424. Lines2D._noCap = 0;
  45425. Lines2D._roundCap = 1;
  45426. Lines2D._triangleCap = 2;
  45427. Lines2D._squareAnchorCap = 3;
  45428. Lines2D._roundAnchorCap = 4;
  45429. Lines2D._diamondAnchorCap = 5;
  45430. Lines2D._arrowCap = 6;
  45431. Lines2D._roundCapSubDiv = 36;
  45432. __decorate([
  45433. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  45434. ], Lines2D.prototype, "points", null);
  45435. __decorate([
  45436. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  45437. ], Lines2D.prototype, "fillThickness", null);
  45438. __decorate([
  45439. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  45440. ], Lines2D.prototype, "closed", null);
  45441. __decorate([
  45442. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  45443. ], Lines2D.prototype, "startCap", null);
  45444. __decorate([
  45445. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  45446. ], Lines2D.prototype, "endCap", null);
  45447. Lines2D = __decorate([
  45448. BABYLON.className("Lines2D")
  45449. ], Lines2D);
  45450. return Lines2D;
  45451. })(BABYLON.Shape2D);
  45452. BABYLON.Lines2D = Lines2D;
  45453. })(BABYLON || (BABYLON = {}));
  45454. var BABYLON;
  45455. (function (BABYLON) {
  45456. // This class contains data that lifetime is bounding to the Babylon Engine object
  45457. var Canvas2DEngineBoundData = (function () {
  45458. function Canvas2DEngineBoundData() {
  45459. this._modelCache = new BABYLON.StringDictionary();
  45460. }
  45461. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  45462. return this._modelCache.getOrAddWithFactory(key, factory);
  45463. };
  45464. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  45465. if (!modelRenderCache.isDisposed) {
  45466. return false;
  45467. }
  45468. this._modelCache.remove(modelRenderCache.modelKey);
  45469. return true;
  45470. };
  45471. return Canvas2DEngineBoundData;
  45472. })();
  45473. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  45474. var Canvas2D = (function (_super) {
  45475. __extends(Canvas2D, _super);
  45476. function Canvas2D(scene, settings) {
  45477. var _this = this;
  45478. _super.call(this, settings);
  45479. /**
  45480. * 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.
  45481. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  45482. */
  45483. this.worldSpaceToNodeLocal = function (worldPos) {
  45484. var node = _this._worldSpaceNode;
  45485. if (!node) {
  45486. return;
  45487. }
  45488. var mtx = node.getWorldMatrix().clone();
  45489. mtx.invert();
  45490. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  45491. var res = new BABYLON.Vector2(v.x, v.y);
  45492. var size = _this.actualSize;
  45493. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  45494. res.y += size.height * 0.5;
  45495. return res;
  45496. };
  45497. /**
  45498. * 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
  45499. */
  45500. this.worldSpaceCacheChanged = function () {
  45501. var plane = _this.worldSpaceCanvasNode;
  45502. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  45503. vd.uvs = new Float32Array(8);
  45504. var material = plane.material;
  45505. var tex = _this._renderableData._cacheTexture;
  45506. if (material.diffuseTexture !== tex) {
  45507. material.diffuseTexture = tex;
  45508. tex.hasAlpha = true;
  45509. }
  45510. var nodeuv = _this._renderableData._cacheNodeUVs;
  45511. for (var i = 0; i < 4; i++) {
  45512. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  45513. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  45514. }
  45515. vd.applyToMesh(plane);
  45516. };
  45517. this._notifDebugMode = false;
  45518. this._mapCounter = 0;
  45519. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  45520. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  45521. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  45522. this._groupRenderCounter = new BABYLON.PerfCounter();
  45523. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  45524. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  45525. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  45526. this._updateLayoutCounter = new BABYLON.PerfCounter();
  45527. this._updatePositioningCounter = new BABYLON.PerfCounter();
  45528. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  45529. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  45530. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  45531. this._profileInfoText = null;
  45532. BABYLON.Prim2DBase._isCanvasInit = false;
  45533. if (!settings) {
  45534. settings = {};
  45535. }
  45536. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  45537. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  45538. this._background.zOrder = 1.0;
  45539. this._background.isPickable = false;
  45540. this._background.origin = BABYLON.Vector2.Zero();
  45541. this._background.levelVisible = false;
  45542. if (settings.backgroundRoundRadius != null) {
  45543. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  45544. }
  45545. if (settings.backgroundBorder != null) {
  45546. if (typeof (settings.backgroundBorder) === "string") {
  45547. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  45548. }
  45549. else {
  45550. this.backgroundBorder = settings.backgroundBorder;
  45551. }
  45552. }
  45553. if (settings.backgroundBorderThickNess != null) {
  45554. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  45555. }
  45556. if (settings.backgroundFill != null) {
  45557. if (typeof (settings.backgroundFill) === "string") {
  45558. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  45559. }
  45560. else {
  45561. this.backgroundFill = settings.backgroundFill;
  45562. }
  45563. }
  45564. this._background._patchHierarchy(this);
  45565. }
  45566. var engine = scene.getEngine();
  45567. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  45568. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  45569. this._capturedPointers = new BABYLON.StringDictionary();
  45570. this._pickStartingPosition = BABYLON.Vector2.Zero();
  45571. this._hierarchyLevelMaxSiblingCount = 50;
  45572. this._hierarchyDepth = 0;
  45573. this._zOrder = 0;
  45574. this._zMax = 1;
  45575. this._scene = scene;
  45576. this._engine = engine;
  45577. this._renderingSize = new BABYLON.Size(0, 0);
  45578. this._trackedGroups = new Array();
  45579. this._maxAdaptiveWorldSpaceCanvasSize = null;
  45580. this._groupCacheMaps = new BABYLON.StringDictionary();
  45581. this._patchHierarchy(this);
  45582. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  45583. this._fitRenderingDevice = !settings.size;
  45584. if (!settings.size) {
  45585. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  45586. }
  45587. // Register scene dispose to also dispose the canvas when it'll happens
  45588. scene.onDisposeObservable.add(function (d, s) {
  45589. _this.dispose();
  45590. });
  45591. if (this._isScreenSpace) {
  45592. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  45593. _this._engine.clear(null, false, true);
  45594. _this._render();
  45595. });
  45596. }
  45597. else {
  45598. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  45599. _this._render();
  45600. });
  45601. }
  45602. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  45603. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  45604. this._setupInteraction(enableInteraction);
  45605. }
  45606. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  45607. get: function () {
  45608. return this._drawCallsOpaqueCounter;
  45609. },
  45610. enumerable: true,
  45611. configurable: true
  45612. });
  45613. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  45614. get: function () {
  45615. return this._drawCallsAlphaTestCounter;
  45616. },
  45617. enumerable: true,
  45618. configurable: true
  45619. });
  45620. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  45621. get: function () {
  45622. return this._drawCallsTransparentCounter;
  45623. },
  45624. enumerable: true,
  45625. configurable: true
  45626. });
  45627. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  45628. get: function () {
  45629. return this._groupRenderCounter;
  45630. },
  45631. enumerable: true,
  45632. configurable: true
  45633. });
  45634. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  45635. get: function () {
  45636. return this._updateTransparentDataCounter;
  45637. },
  45638. enumerable: true,
  45639. configurable: true
  45640. });
  45641. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  45642. get: function () {
  45643. return this._cachedGroupRenderCounter;
  45644. },
  45645. enumerable: true,
  45646. configurable: true
  45647. });
  45648. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  45649. get: function () {
  45650. return this._updateCachedStateCounter;
  45651. },
  45652. enumerable: true,
  45653. configurable: true
  45654. });
  45655. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  45656. get: function () {
  45657. return this._updateLayoutCounter;
  45658. },
  45659. enumerable: true,
  45660. configurable: true
  45661. });
  45662. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  45663. get: function () {
  45664. return this._updatePositioningCounter;
  45665. },
  45666. enumerable: true,
  45667. configurable: true
  45668. });
  45669. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  45670. get: function () {
  45671. return this._updateLocalTransformCounter;
  45672. },
  45673. enumerable: true,
  45674. configurable: true
  45675. });
  45676. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  45677. get: function () {
  45678. return this._updateGlobalTransformCounter;
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  45684. get: function () {
  45685. return this._boundingInfoRecomputeCounter;
  45686. },
  45687. enumerable: true,
  45688. configurable: true
  45689. });
  45690. Canvas2D.prototype._canvasPreInit = function (settings) {
  45691. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  45692. this._cachingStrategy = cachingStrategy;
  45693. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  45694. };
  45695. Canvas2D.prototype._setupInteraction = function (enable) {
  45696. var _this = this;
  45697. // No change detection
  45698. if (enable === this._interactionEnabled) {
  45699. return;
  45700. }
  45701. // Set the new state
  45702. this._interactionEnabled = enable;
  45703. // ScreenSpace mode
  45704. if (this._isScreenSpace) {
  45705. // Disable interaction
  45706. if (!enable) {
  45707. if (this._scenePrePointerObserver) {
  45708. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  45709. this._scenePrePointerObserver = null;
  45710. }
  45711. return;
  45712. }
  45713. // Enable Interaction
  45714. // Register the observable
  45715. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  45716. var hs = 1 / _this.engine.getHardwareScalingLevel();
  45717. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  45718. _this._handlePointerEventForInteraction(e, localPos, s);
  45719. });
  45720. }
  45721. else {
  45722. var scene = this.scene;
  45723. if (enable) {
  45724. scene.constantlyUpdateMeshUnderPointer = true;
  45725. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  45726. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  45727. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  45728. _this._handlePointerEventForInteraction(e, localPos, s);
  45729. }
  45730. });
  45731. }
  45732. else {
  45733. if (this._scenePointerObserver) {
  45734. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  45735. this._scenePointerObserver = null;
  45736. }
  45737. }
  45738. }
  45739. };
  45740. /**
  45741. * Internal method, you should use the Prim2DBase version instead
  45742. */
  45743. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  45744. if (this.isPointerCaptured(pointerId)) {
  45745. return false;
  45746. }
  45747. // Try to capture the pointer on the HTML side
  45748. try {
  45749. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  45750. }
  45751. catch (e) {
  45752. }
  45753. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45754. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  45755. this._capturedPointers.add(pointerId.toString(), primitive);
  45756. return true;
  45757. };
  45758. /**
  45759. * Internal method, you should use the Prim2DBase version instead
  45760. */
  45761. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  45762. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  45763. return false;
  45764. }
  45765. // Try to release the pointer on the HTML side
  45766. try {
  45767. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  45768. }
  45769. catch (e) {
  45770. }
  45771. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  45772. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  45773. this._capturedPointers.remove(pointerId.toString());
  45774. return true;
  45775. };
  45776. /**
  45777. * Determine if the given pointer is captured or not
  45778. * @param pointerId the Id of the pointer
  45779. * @return true if it's captured, false otherwise
  45780. */
  45781. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  45782. return this._capturedPointers.contains(pointerId.toString());
  45783. };
  45784. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  45785. // Avoid unnecessary lookup
  45786. if (this._capturedPointers.count === 0) {
  45787. return null;
  45788. }
  45789. return this._capturedPointers.get(pointerId.toString());
  45790. };
  45791. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  45792. // Dispose check
  45793. if (this.isDisposed) {
  45794. return;
  45795. }
  45796. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  45797. this._updatePointerInfo(eventData, localPosition);
  45798. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45799. // 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.
  45800. // 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.
  45801. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  45802. // 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
  45803. this._updateOverStatus();
  45804. // Check if we have nothing to raise
  45805. if (!this._actualOverPrimitive && !capturedPrim) {
  45806. return;
  45807. }
  45808. // Update the relatedTarget info with the over primitive or the captured one (if any)
  45809. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  45810. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  45811. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  45812. // Analyze the pointer event type and fire proper events on the primitive
  45813. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45814. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  45815. }
  45816. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45817. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  45818. }
  45819. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  45820. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  45821. }
  45822. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  45823. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  45824. }
  45825. };
  45826. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  45827. var pii = this._primPointerInfo;
  45828. if (!pii.canvasPointerPos) {
  45829. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  45830. }
  45831. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  45832. var engine = this._scene.getEngine();
  45833. if (this._isScreenSpace) {
  45834. var cameraViewport = camera.viewport;
  45835. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  45836. // Moving coordinates to local viewport world
  45837. var x = localPosition.x - viewport.x;
  45838. var y = localPosition.y - viewport.y;
  45839. pii.canvasPointerPos.x = x - this.actualPosition.x;
  45840. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  45841. }
  45842. else {
  45843. pii.canvasPointerPos.x = localPosition.x;
  45844. pii.canvasPointerPos.y = localPosition.y;
  45845. }
  45846. pii.mouseWheelDelta = 0;
  45847. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  45848. var event = eventData.event;
  45849. if (event.wheelDelta) {
  45850. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  45851. }
  45852. else if (event.detail) {
  45853. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  45854. }
  45855. }
  45856. else {
  45857. var pe = eventData.event;
  45858. pii.ctrlKey = pe.ctrlKey;
  45859. pii.altKey = pe.altKey;
  45860. pii.shiftKey = pe.shiftKey;
  45861. pii.metaKey = pe.metaKey;
  45862. pii.button = pe.button;
  45863. pii.buttons = pe.buttons;
  45864. pii.pointerId = pe.pointerId;
  45865. pii.width = pe.width;
  45866. pii.height = pe.height;
  45867. pii.presssure = pe.pressure;
  45868. pii.tilt.x = pe.tiltX;
  45869. pii.tilt.y = pe.tiltY;
  45870. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  45871. }
  45872. };
  45873. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  45874. if (this.scene.getRenderId() === this._intersectionRenderId) {
  45875. return;
  45876. }
  45877. // 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
  45878. if (!this._globalTransform) {
  45879. this.updateCachedStates(true);
  45880. }
  45881. var ii = Canvas2D._interInfo;
  45882. ii.pickPosition.x = mouseLocalPos.x;
  45883. ii.pickPosition.y = mouseLocalPos.y;
  45884. ii.findFirstOnly = false;
  45885. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  45886. if (!isCapture && !this.boundingInfo.doesIntersect(ii.pickPosition)) {
  45887. this._previousIntersectionList = this._actualIntersectionList;
  45888. this._actualIntersectionList = null;
  45889. this._previousOverPrimitive = this._actualOverPrimitive;
  45890. this._actualOverPrimitive = null;
  45891. return;
  45892. }
  45893. this.intersect(ii);
  45894. this._previousIntersectionList = this._actualIntersectionList;
  45895. this._actualIntersectionList = ii.intersectedPrimitives;
  45896. this._previousOverPrimitive = this._actualOverPrimitive;
  45897. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  45898. this._intersectionRenderId = this.scene.getRenderId();
  45899. };
  45900. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  45901. Canvas2D.prototype._updateOverStatus = function () {
  45902. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  45903. return;
  45904. }
  45905. // Detect a change of over
  45906. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  45907. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  45908. if (prevPrim !== actualPrim) {
  45909. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  45910. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  45911. // Notify the previous "over" prim that the pointer is no longer over it
  45912. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  45913. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  45914. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  45915. }
  45916. // Notify the new "over" prim that the pointer is over it
  45917. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  45918. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  45919. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  45920. }
  45921. }
  45922. this._hoverStatusRenderId = this.scene.getRenderId();
  45923. };
  45924. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  45925. if (this._primPointerInfo.isCaptured) {
  45926. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  45927. }
  45928. else {
  45929. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  45930. var pii = _a[_i];
  45931. if (pii.prim === prim) {
  45932. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  45933. return;
  45934. }
  45935. }
  45936. }
  45937. };
  45938. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  45939. if (!this._notifDebugMode) {
  45940. return;
  45941. }
  45942. var debug = "";
  45943. for (var i = 0; i < prim.hierarchyDepth; i++) {
  45944. debug += " ";
  45945. }
  45946. var pii = this._primPointerInfo;
  45947. 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();
  45948. console.log(debug);
  45949. };
  45950. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  45951. var ppi = this._primPointerInfo;
  45952. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  45953. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  45954. this._notifParents(prim, mask);
  45955. }
  45956. var bubbleCancelled = false;
  45957. var cur = prim;
  45958. while (cur) {
  45959. // Only trigger the observers if the primitive is intersected (except for out)
  45960. if (!bubbleCancelled) {
  45961. this._updatePrimPointerPos(cur);
  45962. // Exec the observers
  45963. this._debugExecObserver(cur, mask);
  45964. cur._pointerEventObservable.notifyObservers(ppi, mask);
  45965. this._triggerActionManager(cur, ppi, mask, eventData);
  45966. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  45967. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  45968. if (ppi.cancelBubble) {
  45969. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  45970. return;
  45971. }
  45972. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  45973. bubbleCancelled = true;
  45974. }
  45975. }
  45976. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  45977. if (bubbleCancelled) {
  45978. this._updatePrimPointerPos(cur);
  45979. }
  45980. // Trigger a PointerEnter corresponding to the PointerOver
  45981. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  45982. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  45983. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  45984. }
  45985. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  45986. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  45987. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  45988. }
  45989. // Loop to the parent
  45990. cur = cur.parent;
  45991. }
  45992. };
  45993. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  45994. var _this = this;
  45995. // 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
  45996. if (!this._globalTransform) {
  45997. this.updateCachedStates(true);
  45998. }
  45999. // Process Trigger related to PointerDown
  46000. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  46001. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  46002. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  46003. this._pickStartingTime = new Date().getTime();
  46004. this._pickedDownPrim = null;
  46005. if (prim.actionManager) {
  46006. this._pickedDownPrim = prim;
  46007. if (prim.actionManager.hasPickTriggers) {
  46008. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46009. switch (eventData.button) {
  46010. case 0:
  46011. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  46012. break;
  46013. case 1:
  46014. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  46015. break;
  46016. case 2:
  46017. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  46018. break;
  46019. }
  46020. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  46021. }
  46022. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  46023. window.setTimeout(function () {
  46024. var ppi = _this._primPointerInfo;
  46025. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  46026. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  46027. var ii = new BABYLON.IntersectInfo2D();
  46028. ii.pickPosition = ppi.canvasPointerPos.clone();
  46029. ii.findFirstOnly = false;
  46030. _this.intersect(ii);
  46031. if (ii.isPrimIntersected(prim) !== null) {
  46032. if (prim.actionManager) {
  46033. 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)) {
  46034. _this._pickStartingTime = 0;
  46035. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  46036. }
  46037. }
  46038. }
  46039. }, BABYLON.ActionManager.LongPressDelay);
  46040. }
  46041. }
  46042. }
  46043. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  46044. this._pickStartingTime = 0;
  46045. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46046. if (prim.actionManager) {
  46047. // OnPickUpTrigger
  46048. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  46049. // OnPickTrigger
  46050. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  46051. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  46052. }
  46053. }
  46054. // OnPickOutTrigger
  46055. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  46056. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  46057. }
  46058. }
  46059. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  46060. if (prim.actionManager) {
  46061. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46062. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  46063. }
  46064. }
  46065. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  46066. if (prim.actionManager) {
  46067. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  46068. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  46069. }
  46070. }
  46071. };
  46072. Canvas2D.prototype._notifParents = function (prim, mask) {
  46073. var pii = this._primPointerInfo;
  46074. var curPrim = this;
  46075. while (curPrim) {
  46076. this._updatePrimPointerPos(curPrim);
  46077. // Fire the proper notification
  46078. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  46079. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  46080. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  46081. }
  46082. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  46083. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  46084. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  46085. }
  46086. curPrim = curPrim.parent;
  46087. }
  46088. };
  46089. /**
  46090. * Don't forget to call the dispose method when you're done with the Canvas instance.
  46091. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  46092. */
  46093. Canvas2D.prototype.dispose = function () {
  46094. if (!_super.prototype.dispose.call(this)) {
  46095. return false;
  46096. }
  46097. if (this._profilingCanvas) {
  46098. this._profilingCanvas.dispose();
  46099. this._profilingCanvas = null;
  46100. }
  46101. if (this.interactionEnabled) {
  46102. this._setupInteraction(false);
  46103. }
  46104. if (this._beforeRenderObserver) {
  46105. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  46106. this._beforeRenderObserver = null;
  46107. }
  46108. if (this._afterRenderObserver) {
  46109. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  46110. this._afterRenderObserver = null;
  46111. }
  46112. if (this._groupCacheMaps) {
  46113. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  46114. this._groupCacheMaps = null;
  46115. }
  46116. };
  46117. Object.defineProperty(Canvas2D.prototype, "scene", {
  46118. /**
  46119. * Accessor to the Scene that owns the Canvas
  46120. * @returns The instance of the Scene object
  46121. */
  46122. get: function () {
  46123. return this._scene;
  46124. },
  46125. enumerable: true,
  46126. configurable: true
  46127. });
  46128. Object.defineProperty(Canvas2D.prototype, "engine", {
  46129. /**
  46130. * Accessor to the Engine that drives the Scene used by this Canvas
  46131. * @returns The instance of the Engine object
  46132. */
  46133. get: function () {
  46134. return this._engine;
  46135. },
  46136. enumerable: true,
  46137. configurable: true
  46138. });
  46139. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  46140. /**
  46141. * Accessor of the Caching Strategy used by this Canvas.
  46142. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  46143. * @returns the value corresponding to the used strategy.
  46144. */
  46145. get: function () {
  46146. return this._cachingStrategy;
  46147. },
  46148. enumerable: true,
  46149. configurable: true
  46150. });
  46151. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  46152. /**
  46153. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  46154. * @returns {}
  46155. */
  46156. get: function () {
  46157. return this._isScreenSpace;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  46163. /**
  46164. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  46165. */
  46166. get: function () {
  46167. return this._worldSpaceNode;
  46168. },
  46169. set: function (val) {
  46170. this._worldSpaceNode = val;
  46171. },
  46172. enumerable: true,
  46173. configurable: true
  46174. });
  46175. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  46176. /**
  46177. * Check if the WebGL Instanced Array extension is supported or not
  46178. */
  46179. get: function () {
  46180. return this._supprtInstancedArray;
  46181. },
  46182. enumerable: true,
  46183. configurable: true
  46184. });
  46185. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  46186. /**
  46187. * Property that defines the fill object used to draw the background of the Canvas.
  46188. * Note that Canvas with a Caching Strategy of
  46189. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  46190. */
  46191. get: function () {
  46192. if (!this._background || !this._background.isVisible) {
  46193. return null;
  46194. }
  46195. return this._background.fill;
  46196. },
  46197. set: function (value) {
  46198. this.checkBackgroundAvailability();
  46199. if (value === this._background.fill) {
  46200. return;
  46201. }
  46202. this._background.fill = value;
  46203. this._background.levelVisible = true;
  46204. },
  46205. enumerable: true,
  46206. configurable: true
  46207. });
  46208. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  46209. /**
  46210. * Property that defines the border object used to draw the background of the Canvas.
  46211. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  46212. */
  46213. get: function () {
  46214. if (!this._background || !this._background.isVisible) {
  46215. return null;
  46216. }
  46217. return this._background.border;
  46218. },
  46219. set: function (value) {
  46220. this.checkBackgroundAvailability();
  46221. if (value === this._background.border) {
  46222. return;
  46223. }
  46224. this._background.border = value;
  46225. this._background.levelVisible = true;
  46226. },
  46227. enumerable: true,
  46228. configurable: true
  46229. });
  46230. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  46231. /**
  46232. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  46233. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  46234. */
  46235. get: function () {
  46236. if (!this._background || !this._background.isVisible) {
  46237. return null;
  46238. }
  46239. return this._background.borderThickness;
  46240. },
  46241. set: function (value) {
  46242. this.checkBackgroundAvailability();
  46243. if (value === this._background.borderThickness) {
  46244. return;
  46245. }
  46246. this._background.borderThickness = value;
  46247. },
  46248. enumerable: true,
  46249. configurable: true
  46250. });
  46251. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  46252. /**
  46253. * You can set the roundRadius of the background
  46254. * @returns The current roundRadius
  46255. */
  46256. get: function () {
  46257. if (!this._background || !this._background.isVisible) {
  46258. return null;
  46259. }
  46260. return this._background.roundRadius;
  46261. },
  46262. set: function (value) {
  46263. this.checkBackgroundAvailability();
  46264. if (value === this._background.roundRadius) {
  46265. return;
  46266. }
  46267. this._background.roundRadius = value;
  46268. this._background.levelVisible = true;
  46269. },
  46270. enumerable: true,
  46271. configurable: true
  46272. });
  46273. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  46274. /**
  46275. * Enable/Disable interaction for this Canvas
  46276. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  46277. */
  46278. get: function () {
  46279. return this._interactionEnabled;
  46280. },
  46281. set: function (enable) {
  46282. this._setupInteraction(enable);
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  46288. /**
  46289. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  46290. * @returns {}
  46291. */
  46292. get: function () {
  46293. return this.__engineData;
  46294. },
  46295. enumerable: true,
  46296. configurable: true
  46297. });
  46298. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  46299. if (this._profilingCanvas) {
  46300. return this._profilingCanvas;
  46301. }
  46302. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  46303. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  46304. new BABYLON.Rectangle2D({
  46305. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  46306. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  46307. ]
  46308. })
  46309. ]
  46310. });
  46311. this._profileInfoText = canvas.findById("ProfileInfoText");
  46312. this._profilingCanvas = canvas;
  46313. return canvas;
  46314. };
  46315. Canvas2D.prototype.checkBackgroundAvailability = function () {
  46316. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  46317. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  46318. }
  46319. };
  46320. Canvas2D.prototype._initPerfMetrics = function () {
  46321. this._drawCallsOpaqueCounter.fetchNewFrame();
  46322. this._drawCallsAlphaTestCounter.fetchNewFrame();
  46323. this._drawCallsTransparentCounter.fetchNewFrame();
  46324. this._groupRenderCounter.fetchNewFrame();
  46325. this._updateTransparentDataCounter.fetchNewFrame();
  46326. this._cachedGroupRenderCounter.fetchNewFrame();
  46327. this._updateCachedStateCounter.fetchNewFrame();
  46328. this._updateLayoutCounter.fetchNewFrame();
  46329. this._updatePositioningCounter.fetchNewFrame();
  46330. this._updateLocalTransformCounter.fetchNewFrame();
  46331. this._updateGlobalTransformCounter.fetchNewFrame();
  46332. this._boundingInfoRecomputeCounter.fetchNewFrame();
  46333. };
  46334. Canvas2D.prototype._fetchPerfMetrics = function () {
  46335. this._drawCallsOpaqueCounter.addCount(0, true);
  46336. this._drawCallsAlphaTestCounter.addCount(0, true);
  46337. this._drawCallsTransparentCounter.addCount(0, true);
  46338. this._groupRenderCounter.addCount(0, true);
  46339. this._updateTransparentDataCounter.addCount(0, true);
  46340. this._cachedGroupRenderCounter.addCount(0, true);
  46341. this._updateCachedStateCounter.addCount(0, true);
  46342. this._updateLayoutCounter.addCount(0, true);
  46343. this._updatePositioningCounter.addCount(0, true);
  46344. this._updateLocalTransformCounter.addCount(0, true);
  46345. this._updateGlobalTransformCounter.addCount(0, true);
  46346. this._boundingInfoRecomputeCounter.addCount(0, true);
  46347. };
  46348. Canvas2D.prototype._updateProfileCanvas = function () {
  46349. if (this._profileInfoText == null) {
  46350. return;
  46351. }
  46352. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  46353. var p = "Draw Calls:\n" +
  46354. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  46355. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  46356. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  46357. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  46358. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  46359. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  46360. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  46361. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  46362. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  46363. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  46364. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  46365. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  46366. this._profileInfoText.text = p;
  46367. };
  46368. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  46369. switch (renderMode) {
  46370. case BABYLON.Render2DContext.RenderModeOpaque:
  46371. this._drawCallsOpaqueCounter.addCount(count, false);
  46372. return;
  46373. case BABYLON.Render2DContext.RenderModeAlphaTest:
  46374. this._drawCallsAlphaTestCounter.addCount(count, false);
  46375. return;
  46376. case BABYLON.Render2DContext.RenderModeTransparent:
  46377. this._drawCallsTransparentCounter.addCount(count, false);
  46378. return;
  46379. }
  46380. };
  46381. Canvas2D.prototype._addGroupRenderCount = function (count) {
  46382. this._groupRenderCounter.addCount(count, false);
  46383. };
  46384. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  46385. this._updateTransparentDataCounter.addCount(count, false);
  46386. };
  46387. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  46388. this._cachedGroupRenderCounter.addCount(count, false);
  46389. };
  46390. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  46391. this._updateCachedStateCounter.addCount(count, false);
  46392. };
  46393. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  46394. this._updateLayoutCounter.addCount(count, false);
  46395. };
  46396. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  46397. this._updatePositioningCounter.addCount(count, false);
  46398. };
  46399. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  46400. this._updateLocalTransformCounter.addCount(count, false);
  46401. };
  46402. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  46403. this._updateGlobalTransformCounter.addCount(count, false);
  46404. };
  46405. Canvas2D.prototype.onPrimBecomesDirty = function () {
  46406. this._addPrimToDirtyList(this);
  46407. };
  46408. Canvas2D.prototype._updateTrackedNodes = function () {
  46409. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46410. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46411. var rh = this.engine.getRenderHeight();
  46412. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  46413. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  46414. var group = _a[_i];
  46415. if (group.isDisposed || !group.isVisible) {
  46416. continue;
  46417. }
  46418. var node = group.trackedNode;
  46419. var worldMtx = node.getWorldMatrix();
  46420. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  46421. group.x = Math.round(proj.x);
  46422. group.y = Math.round(rh - proj.y);
  46423. }
  46424. };
  46425. /**
  46426. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  46427. */
  46428. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  46429. this._updateCanvasState(forceRecompute);
  46430. };
  46431. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  46432. if (this._globalTransformStep < 2) {
  46433. return;
  46434. }
  46435. var n = this.worldSpaceCanvasNode;
  46436. var bi = n.getBoundingInfo().boundingBox;
  46437. var v = bi.vectorsWorld;
  46438. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  46439. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  46440. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  46441. var projPoints = new Array(4);
  46442. for (var i = 0; i < 4; i++) {
  46443. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  46444. }
  46445. var left = projPoints[3].subtract(projPoints[0]).length();
  46446. var top = projPoints[3].subtract(projPoints[1]).length();
  46447. var right = projPoints[1].subtract(projPoints[2]).length();
  46448. var bottom = projPoints[2].subtract(projPoints[0]).length();
  46449. var w = Math.round(Math.max(top, bottom));
  46450. var h = Math.round(Math.max(right, left));
  46451. var isW = w > h;
  46452. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  46453. var edge = Math.max(w, h);
  46454. if (edge < 256) {
  46455. edge = 256;
  46456. }
  46457. else {
  46458. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  46459. }
  46460. // Clip values if needed
  46461. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  46462. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  46463. if (newScale !== this.scale) {
  46464. var scale = newScale;
  46465. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  46466. this._setRenderingScale(scale);
  46467. }
  46468. };
  46469. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  46470. // Check if the update has already been made for this render Frame
  46471. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  46472. return;
  46473. }
  46474. // Detect a change of rendering size
  46475. var renderingSizeChanged = false;
  46476. var newWidth = this.engine.getRenderWidth();
  46477. if (newWidth !== this._renderingSize.width) {
  46478. renderingSizeChanged = true;
  46479. }
  46480. this._renderingSize.width = newWidth;
  46481. var newHeight = this.engine.getRenderHeight();
  46482. if (newHeight !== this._renderingSize.height) {
  46483. renderingSizeChanged = true;
  46484. }
  46485. this._renderingSize.height = newHeight;
  46486. // If the canvas fit the rendering size and it changed, update
  46487. if (renderingSizeChanged && this._fitRenderingDevice) {
  46488. this.size = this._renderingSize;
  46489. if (this._background) {
  46490. this._background.size = this.size;
  46491. }
  46492. // Dirty the Layout at the Canvas level to recompute as the size changed
  46493. this._setLayoutDirty();
  46494. }
  46495. var context = new BABYLON.PrepareRender2DContext();
  46496. ++this._globalTransformProcessStep;
  46497. this.updateCachedStates(false);
  46498. this._prepareGroupRender(context);
  46499. this._updateRenderId = this.scene.getRenderId();
  46500. };
  46501. /**
  46502. * Method that renders the Canvas, you should not invoke
  46503. */
  46504. Canvas2D.prototype._render = function () {
  46505. this._initPerfMetrics();
  46506. this._updateTrackedNodes();
  46507. this._updateCanvasState(false);
  46508. if (!this._isScreenSpace) {
  46509. this._updateAdaptiveSizeWorldCanvas();
  46510. }
  46511. this._updateCanvasState(false);
  46512. if (this._primPointerInfo.canvasPointerPos) {
  46513. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  46514. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  46515. }
  46516. this.engine.setState(false);
  46517. this._groupRender();
  46518. if (!this._isScreenSpace) {
  46519. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  46520. this.worldSpaceCacheChanged();
  46521. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  46522. }
  46523. }
  46524. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  46525. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  46526. this._cachedCanvasGroup._renderCachedCanvas();
  46527. }
  46528. this._fetchPerfMetrics();
  46529. this._updateProfileCanvas();
  46530. };
  46531. /**
  46532. * Internal method that allocate a cache for the given group.
  46533. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  46534. * @param group The group to allocate the cache of.
  46535. * @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.
  46536. */
  46537. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  46538. if (useMipMap === void 0) { useMipMap = false; }
  46539. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  46540. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  46541. // Determine size
  46542. var size = group.actualSize;
  46543. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  46544. if (minSize) {
  46545. size.width = Math.max(minSize.width, size.width);
  46546. size.height = Math.max(minSize.height, size.height);
  46547. }
  46548. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  46549. // Try to find a spot in one of the cached texture
  46550. var res = null;
  46551. var map;
  46552. for (var _i = 0; _i < mapArray.length; _i++) {
  46553. var _map = mapArray[_i];
  46554. map = _map;
  46555. var node = map.allocateRect(size);
  46556. if (node) {
  46557. res = { node: node, texture: map };
  46558. break;
  46559. }
  46560. }
  46561. // Couldn't find a map that could fit the rect, create a new map for it
  46562. if (!res) {
  46563. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  46564. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  46565. if (size.width > mapSize.width || size.height > mapSize.height) {
  46566. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  46567. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  46568. }
  46569. var id = "groupsMapChache" + this._mapCounter + "forCanvas" + this.id;
  46570. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  46571. map.anisotropicFilteringLevel = 4;
  46572. mapArray.splice(0, 0, map);
  46573. var node = map.allocateRect(size);
  46574. res = { node: node, texture: map };
  46575. }
  46576. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  46577. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  46578. if (group !== this || this._isScreenSpace) {
  46579. var node = res.node;
  46580. // 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
  46581. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  46582. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  46583. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  46584. sprite.zOrder = 1;
  46585. sprite.origin = BABYLON.Vector2.Zero();
  46586. }
  46587. else {
  46588. 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 });
  46589. sprite.origin = group.origin.clone();
  46590. res.sprite = sprite;
  46591. }
  46592. }
  46593. return res;
  46594. };
  46595. /**
  46596. * Internal method used to register a Scene Node to track position for the given group
  46597. * Do not invoke this method, for internal purpose only.
  46598. * @param group the group to track its associated Scene Node
  46599. */
  46600. Canvas2D.prototype._registerTrackedNode = function (group) {
  46601. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46602. return;
  46603. }
  46604. this._trackedGroups.push(group);
  46605. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46606. };
  46607. /**
  46608. * Internal method used to unregister a tracked Scene Node
  46609. * Do not invoke this method, it's for internal purpose only.
  46610. * @param group the group to unregister its tracked Scene Node from.
  46611. */
  46612. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  46613. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  46614. return;
  46615. }
  46616. var i = this._trackedGroups.indexOf(group);
  46617. if (i !== -1) {
  46618. this._trackedGroups.splice(i, 1);
  46619. }
  46620. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  46621. };
  46622. /**
  46623. * Get a Solid Color Brush instance matching the given color.
  46624. * @param color The color to retrieve
  46625. * @return A shared instance of the SolidColorBrush2D class that use the given color
  46626. */
  46627. Canvas2D.GetSolidColorBrush = function (color) {
  46628. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  46629. };
  46630. /**
  46631. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  46632. * @param color The color to retrieve
  46633. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  46634. */
  46635. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  46636. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  46637. };
  46638. /**
  46639. * Get a Gradient Color Brush
  46640. * @param color1 starting color
  46641. * @param color2 engine color
  46642. * @param translation translation vector to apply. default is [0;0]
  46643. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  46644. * @param scale scaling factor to apply. default is 1.
  46645. */
  46646. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  46647. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  46648. if (rotation === void 0) { rotation = 0; }
  46649. if (scale === void 0) { scale = 1; }
  46650. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  46651. };
  46652. /**
  46653. * Create a solid or gradient brush from a string value.
  46654. * @param brushString should be either
  46655. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  46656. * - "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.
  46657. */
  46658. Canvas2D.GetBrushFromString = function (brushString) {
  46659. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  46660. brushString = brushString.trim();
  46661. var split = brushString.split(",");
  46662. // Solid, formatted as: "[solid:]#FF808080"
  46663. if (split.length === 1) {
  46664. var value = null;
  46665. if (brushString.indexOf("solid:") === 0) {
  46666. value = brushString.substr(6).trim();
  46667. }
  46668. else if (brushString.indexOf("#") === 0) {
  46669. value = brushString;
  46670. }
  46671. else {
  46672. return null;
  46673. }
  46674. return Canvas2D.GetSolidColorBrushFromHex(value);
  46675. }
  46676. else {
  46677. if (split[0].indexOf("gradient:") === 0) {
  46678. split[0] = split[0].substr(9).trim();
  46679. }
  46680. try {
  46681. var start = BABYLON.Color4.FromHexString(split[0].trim());
  46682. var end = BABYLON.Color4.FromHexString(split[1].trim());
  46683. var t = BABYLON.Vector2.Zero();
  46684. if (split.length > 2) {
  46685. var v = split[2].trim();
  46686. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  46687. return null;
  46688. }
  46689. var sep = v.indexOf(":");
  46690. var x = parseFloat(v.substr(1, sep));
  46691. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  46692. t = new BABYLON.Vector2(x, y);
  46693. }
  46694. var r = 0;
  46695. if (split.length > 3) {
  46696. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  46697. }
  46698. var s = 1;
  46699. if (split.length > 4) {
  46700. s = parseFloat(split[4].trim());
  46701. }
  46702. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  46703. }
  46704. catch (e) {
  46705. return null;
  46706. }
  46707. }
  46708. };
  46709. /**
  46710. * 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.
  46711. * This strategy doesn't allow primitives added directly as children of the Canvas.
  46712. * 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.
  46713. */
  46714. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  46715. /**
  46716. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  46717. * 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.
  46718. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  46719. * 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.
  46720. */
  46721. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  46722. /**
  46723. * 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).
  46724. */
  46725. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  46726. /**
  46727. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  46728. * 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).
  46729. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  46730. */
  46731. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  46732. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  46733. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  46734. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  46735. Canvas2D._m = BABYLON.Matrix.Identity();
  46736. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  46737. /**
  46738. * Define the default size used for both the width and height of a MapTexture to allocate.
  46739. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  46740. */
  46741. Canvas2D._groupTextureCacheSize = 1024;
  46742. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  46743. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  46744. Canvas2D = __decorate([
  46745. BABYLON.className("Canvas2D")
  46746. ], Canvas2D);
  46747. return Canvas2D;
  46748. })(BABYLON.Group2D);
  46749. BABYLON.Canvas2D = Canvas2D;
  46750. var WorldSpaceCanvas2D = (function (_super) {
  46751. __extends(WorldSpaceCanvas2D, _super);
  46752. /**
  46753. * 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.
  46754. * 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.
  46755. * @param scene the Scene that owns the Canvas
  46756. * @param size the dimension of the Canvas in World Space
  46757. * @param settings a combination of settings, possible ones are
  46758. * - children: an array of direct children primitives
  46759. * - id: a text identifier, for information purpose only, default is null.
  46760. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  46761. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  46762. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  46763. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  46764. * - 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).
  46765. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46766. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46767. * - 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.
  46768. * - 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.
  46769. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46770. * - 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.
  46771. * - 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.
  46772. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46773. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46774. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46775. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46776. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46777. */
  46778. function WorldSpaceCanvas2D(scene, size, settings) {
  46779. BABYLON.Prim2DBase._isCanvasInit = true;
  46780. var s = settings;
  46781. s.isScreenSpace = false;
  46782. s.size = size.clone();
  46783. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  46784. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  46785. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  46786. }
  46787. _super.call(this, scene, settings);
  46788. BABYLON.Prim2DBase._isCanvasInit = false;
  46789. this._renderableData._useMipMap = true;
  46790. this._renderableData._anisotropicLevel = 8;
  46791. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  46792. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  46793. //}
  46794. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  46795. var id = settings ? settings.id || null : null;
  46796. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  46797. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  46798. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  46799. if (settings.maxAdaptiveCanvasSize == null) {
  46800. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  46801. }
  46802. else {
  46803. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  46804. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  46805. }
  46806. if (createWorldSpaceNode) {
  46807. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  46808. var vertexData = BABYLON.VertexData.CreatePlane({
  46809. width: size.width,
  46810. height: size.height,
  46811. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  46812. });
  46813. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  46814. this.applyCachedTexture(vertexData, mtl);
  46815. vertexData.applyToMesh(plane, true);
  46816. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  46817. mtl.disableLighting = true;
  46818. mtl.useAlphaFromDiffuseTexture = true;
  46819. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  46820. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  46821. plane.material = mtl;
  46822. this._worldSpaceNode = plane;
  46823. }
  46824. else {
  46825. this._worldSpaceNode = settings.customWorldSpaceNode;
  46826. this.applyCachedTexture(null, null);
  46827. }
  46828. }
  46829. WorldSpaceCanvas2D = __decorate([
  46830. BABYLON.className("WorldSpaceCanvas2D")
  46831. ], WorldSpaceCanvas2D);
  46832. return WorldSpaceCanvas2D;
  46833. })(Canvas2D);
  46834. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  46835. var ScreenSpaceCanvas2D = (function (_super) {
  46836. __extends(ScreenSpaceCanvas2D, _super);
  46837. /**
  46838. * 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.
  46839. * 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.
  46840. * All caching strategies will be available.
  46841. * 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]
  46842. * @param scene the Scene that owns the Canvas
  46843. * @param settings a combination of settings, possible ones are
  46844. * - children: an array of direct children primitives
  46845. * - id: a text identifier, for information purpose only
  46846. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  46847. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  46848. * - 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]
  46849. * - width: the width of the Canvas. you can alternatively use the size setting.
  46850. * - height: the height of the Canvas. you can alternatively use the size setting.
  46851. * - 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
  46852. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  46853. * - 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.
  46854. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  46855. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  46856. * - 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.
  46857. * - 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.
  46858. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  46859. * - 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.
  46860. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46861. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46862. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46863. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  46864. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  46865. */
  46866. function ScreenSpaceCanvas2D(scene, settings) {
  46867. BABYLON.Prim2DBase._isCanvasInit = true;
  46868. _super.call(this, scene, settings);
  46869. }
  46870. ScreenSpaceCanvas2D = __decorate([
  46871. BABYLON.className("ScreenSpaceCanvas2D")
  46872. ], ScreenSpaceCanvas2D);
  46873. return ScreenSpaceCanvas2D;
  46874. })(Canvas2D);
  46875. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  46876. })(BABYLON || (BABYLON = {}));
  46877. var BABYLON;
  46878. (function (BABYLON) {
  46879. /**
  46880. * This is the class that is used to display a World Space Canvas into a 3D scene
  46881. */
  46882. var WorldSpaceCanvas2DNode = (function (_super) {
  46883. __extends(WorldSpaceCanvas2DNode, _super);
  46884. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  46885. _super.call(this, name, scene);
  46886. this._canvas = canvas;
  46887. }
  46888. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  46889. _super.prototype.dispose.call(this);
  46890. if (this._canvas) {
  46891. this._canvas.dispose();
  46892. this._canvas = null;
  46893. }
  46894. };
  46895. return WorldSpaceCanvas2DNode;
  46896. })(BABYLON.Mesh);
  46897. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  46898. })(BABYLON || (BABYLON = {}));
  46899. var BABYLON;
  46900. (function (BABYLON) {
  46901. var LayoutEngineBase = (function () {
  46902. function LayoutEngineBase() {
  46903. this.layoutDirtyOnPropertyChangedMask = 0;
  46904. }
  46905. LayoutEngineBase.prototype.updateLayout = function (prim) {
  46906. };
  46907. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  46908. get: function () {
  46909. return false;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. LayoutEngineBase.prototype.isLocked = function () {
  46915. return this._isLocked;
  46916. };
  46917. LayoutEngineBase.prototype.lock = function () {
  46918. if (this._isLocked) {
  46919. return false;
  46920. }
  46921. this._isLocked = true;
  46922. return true;
  46923. };
  46924. LayoutEngineBase = __decorate([
  46925. BABYLON.className("LayoutEngineBase")
  46926. ], LayoutEngineBase);
  46927. return LayoutEngineBase;
  46928. })();
  46929. BABYLON.LayoutEngineBase = LayoutEngineBase;
  46930. var CanvasLayoutEngine = (function (_super) {
  46931. __extends(CanvasLayoutEngine, _super);
  46932. function CanvasLayoutEngine() {
  46933. _super.apply(this, arguments);
  46934. }
  46935. // A very simple (no) layout computing...
  46936. // The Canvas and its direct children gets the Canvas' size as Layout Area
  46937. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  46938. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  46939. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  46940. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  46941. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  46942. var child = _a[_i];
  46943. this._doUpdate(child);
  46944. }
  46945. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  46946. }
  46947. };
  46948. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  46949. // Canvas ?
  46950. if (prim instanceof BABYLON.Canvas2D) {
  46951. prim.layoutArea = prim.actualSize;
  46952. }
  46953. else if (prim.parent instanceof BABYLON.Canvas2D) {
  46954. prim.layoutArea = prim.owner.actualSize;
  46955. }
  46956. else {
  46957. prim.layoutArea = prim.parent.contentArea;
  46958. }
  46959. };
  46960. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  46961. get: function () {
  46962. return true;
  46963. },
  46964. enumerable: true,
  46965. configurable: true
  46966. });
  46967. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  46968. CanvasLayoutEngine = __decorate([
  46969. BABYLON.className("CanvasLayoutEngine")
  46970. ], CanvasLayoutEngine);
  46971. return CanvasLayoutEngine;
  46972. })(LayoutEngineBase);
  46973. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  46974. var StackPanelLayoutEngine = (function (_super) {
  46975. __extends(StackPanelLayoutEngine, _super);
  46976. function StackPanelLayoutEngine() {
  46977. _super.call(this);
  46978. this._isHorizontal = true;
  46979. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  46980. }
  46981. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  46982. get: function () {
  46983. if (!StackPanelLayoutEngine._horizontal) {
  46984. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  46985. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  46986. StackPanelLayoutEngine._horizontal.lock();
  46987. }
  46988. return StackPanelLayoutEngine._horizontal;
  46989. },
  46990. enumerable: true,
  46991. configurable: true
  46992. });
  46993. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  46994. get: function () {
  46995. if (!StackPanelLayoutEngine._vertical) {
  46996. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  46997. StackPanelLayoutEngine._vertical.isHorizontal = false;
  46998. StackPanelLayoutEngine._vertical.lock();
  46999. }
  47000. return StackPanelLayoutEngine._vertical;
  47001. },
  47002. enumerable: true,
  47003. configurable: true
  47004. });
  47005. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  47006. get: function () {
  47007. return this._isHorizontal;
  47008. },
  47009. set: function (val) {
  47010. if (this.isLocked()) {
  47011. return;
  47012. }
  47013. this._isHorizontal = val;
  47014. },
  47015. enumerable: true,
  47016. configurable: true
  47017. });
  47018. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  47019. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  47020. var x = 0;
  47021. var y = 0;
  47022. var h = this.isHorizontal;
  47023. var max = 0;
  47024. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  47025. var child = _a[_i];
  47026. var layoutArea = child.layoutArea;
  47027. child.margin.computeArea(child.actualSize, layoutArea);
  47028. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  47029. }
  47030. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  47031. var child = _c[_b];
  47032. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  47033. var layoutArea = child.layoutArea;
  47034. if (h) {
  47035. x += layoutArea.width;
  47036. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  47037. }
  47038. else {
  47039. y += layoutArea.height;
  47040. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  47041. }
  47042. }
  47043. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  47044. }
  47045. };
  47046. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  47047. get: function () {
  47048. return false;
  47049. },
  47050. enumerable: true,
  47051. configurable: true
  47052. });
  47053. StackPanelLayoutEngine._horizontal = null;
  47054. StackPanelLayoutEngine._vertical = null;
  47055. StackPanelLayoutEngine = __decorate([
  47056. BABYLON.className("StackPanelLayoutEngine")
  47057. ], StackPanelLayoutEngine);
  47058. return StackPanelLayoutEngine;
  47059. })(LayoutEngineBase);
  47060. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  47061. })(BABYLON || (BABYLON = {}));
  47062. var BABYLON;
  47063. (function (BABYLON) {
  47064. var ShaderMaterial = (function (_super) {
  47065. __extends(ShaderMaterial, _super);
  47066. function ShaderMaterial(name, scene, shaderPath, options) {
  47067. _super.call(this, name, scene);
  47068. this._textures = {};
  47069. this._textureArrays = {};
  47070. this._floats = {};
  47071. this._floatsArrays = {};
  47072. this._colors3 = {};
  47073. this._colors4 = {};
  47074. this._vectors2 = {};
  47075. this._vectors3 = {};
  47076. this._vectors4 = {};
  47077. this._matrices = {};
  47078. this._matrices3x3 = {};
  47079. this._matrices2x2 = {};
  47080. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47081. this._shaderPath = shaderPath;
  47082. options.needAlphaBlending = options.needAlphaBlending || false;
  47083. options.needAlphaTesting = options.needAlphaTesting || false;
  47084. options.attributes = options.attributes || ["position", "normal", "uv"];
  47085. options.uniforms = options.uniforms || ["worldViewProjection"];
  47086. options.samplers = options.samplers || [];
  47087. options.defines = options.defines || [];
  47088. this._options = options;
  47089. }
  47090. ShaderMaterial.prototype.needAlphaBlending = function () {
  47091. return this._options.needAlphaBlending;
  47092. };
  47093. ShaderMaterial.prototype.needAlphaTesting = function () {
  47094. return this._options.needAlphaTesting;
  47095. };
  47096. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47097. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47098. this._options.uniforms.push(uniformName);
  47099. }
  47100. };
  47101. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47102. if (this._options.samplers.indexOf(name) === -1) {
  47103. this._options.samplers.push(name);
  47104. }
  47105. this._textures[name] = texture;
  47106. return this;
  47107. };
  47108. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47109. if (this._options.samplers.indexOf(name) === -1) {
  47110. this._options.samplers.push(name);
  47111. }
  47112. this._checkUniform(name);
  47113. this._textureArrays[name] = textures;
  47114. return this;
  47115. };
  47116. ShaderMaterial.prototype.setFloat = function (name, value) {
  47117. this._checkUniform(name);
  47118. this._floats[name] = value;
  47119. return this;
  47120. };
  47121. ShaderMaterial.prototype.setFloats = function (name, value) {
  47122. this._checkUniform(name);
  47123. this._floatsArrays[name] = value;
  47124. return this;
  47125. };
  47126. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47127. this._checkUniform(name);
  47128. this._colors3[name] = value;
  47129. return this;
  47130. };
  47131. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47132. this._checkUniform(name);
  47133. this._colors4[name] = value;
  47134. return this;
  47135. };
  47136. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47137. this._checkUniform(name);
  47138. this._vectors2[name] = value;
  47139. return this;
  47140. };
  47141. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47142. this._checkUniform(name);
  47143. this._vectors3[name] = value;
  47144. return this;
  47145. };
  47146. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47147. this._checkUniform(name);
  47148. this._vectors4[name] = value;
  47149. return this;
  47150. };
  47151. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47152. this._checkUniform(name);
  47153. this._matrices[name] = value;
  47154. return this;
  47155. };
  47156. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47157. this._checkUniform(name);
  47158. this._matrices3x3[name] = value;
  47159. return this;
  47160. };
  47161. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47162. this._checkUniform(name);
  47163. this._matrices2x2[name] = value;
  47164. return this;
  47165. };
  47166. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47167. var scene = this.getScene();
  47168. var engine = scene.getEngine();
  47169. if (!this.checkReadyOnEveryCall) {
  47170. if (this._renderId === scene.getRenderId()) {
  47171. return true;
  47172. }
  47173. }
  47174. // Instances
  47175. var defines = [];
  47176. var fallbacks = new BABYLON.EffectFallbacks();
  47177. if (useInstances) {
  47178. defines.push("#define INSTANCES");
  47179. }
  47180. for (var index = 0; index < this._options.defines.length; index++) {
  47181. defines.push(this._options.defines[index]);
  47182. }
  47183. // Bones
  47184. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47185. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47186. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47187. fallbacks.addCPUSkinningFallback(0, mesh);
  47188. }
  47189. // Alpha test
  47190. if (engine.getAlphaTesting()) {
  47191. defines.push("#define ALPHATEST");
  47192. }
  47193. var previousEffect = this._effect;
  47194. var join = defines.join("\n");
  47195. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  47196. if (!this._effect.isReady()) {
  47197. return false;
  47198. }
  47199. if (previousEffect !== this._effect) {
  47200. scene.resetCachedMaterial();
  47201. }
  47202. this._renderId = scene.getRenderId();
  47203. return true;
  47204. };
  47205. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47206. var scene = this.getScene();
  47207. if (this._options.uniforms.indexOf("world") !== -1) {
  47208. this._effect.setMatrix("world", world);
  47209. }
  47210. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47211. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47212. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47213. }
  47214. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47215. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47216. }
  47217. };
  47218. ShaderMaterial.prototype.bind = function (world, mesh) {
  47219. // Std values
  47220. this.bindOnlyWorldMatrix(world);
  47221. if (this.getScene().getCachedMaterial() !== this) {
  47222. if (this._options.uniforms.indexOf("view") !== -1) {
  47223. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47224. }
  47225. if (this._options.uniforms.indexOf("projection") !== -1) {
  47226. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47227. }
  47228. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47229. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47230. }
  47231. // Bones
  47232. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  47233. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47234. }
  47235. var name;
  47236. // Texture
  47237. for (name in this._textures) {
  47238. this._effect.setTexture(name, this._textures[name]);
  47239. }
  47240. // Texture arrays
  47241. for (name in this._textureArrays) {
  47242. this._effect.setTextureArray(name, this._textureArrays[name]);
  47243. }
  47244. // Float
  47245. for (name in this._floats) {
  47246. this._effect.setFloat(name, this._floats[name]);
  47247. }
  47248. // Float s
  47249. for (name in this._floatsArrays) {
  47250. this._effect.setArray(name, this._floatsArrays[name]);
  47251. }
  47252. // Color3
  47253. for (name in this._colors3) {
  47254. this._effect.setColor3(name, this._colors3[name]);
  47255. }
  47256. // Color4
  47257. for (name in this._colors4) {
  47258. var color = this._colors4[name];
  47259. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47260. }
  47261. // Vector2
  47262. for (name in this._vectors2) {
  47263. this._effect.setVector2(name, this._vectors2[name]);
  47264. }
  47265. // Vector3
  47266. for (name in this._vectors3) {
  47267. this._effect.setVector3(name, this._vectors3[name]);
  47268. }
  47269. // Vector4
  47270. for (name in this._vectors4) {
  47271. this._effect.setVector4(name, this._vectors4[name]);
  47272. }
  47273. // Matrix
  47274. for (name in this._matrices) {
  47275. this._effect.setMatrix(name, this._matrices[name]);
  47276. }
  47277. // Matrix 3x3
  47278. for (name in this._matrices3x3) {
  47279. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47280. }
  47281. // Matrix 2x2
  47282. for (name in this._matrices2x2) {
  47283. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47284. }
  47285. }
  47286. _super.prototype.bind.call(this, world, mesh);
  47287. };
  47288. ShaderMaterial.prototype.clone = function (name) {
  47289. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47290. return newShaderMaterial;
  47291. };
  47292. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47293. if (forceDisposeTextures) {
  47294. var name;
  47295. for (name in this._textures) {
  47296. this._textures[name].dispose();
  47297. }
  47298. for (name in this._textureArrays) {
  47299. var array = this._textureArrays[name];
  47300. for (var index = 0; index < array.length; index++) {
  47301. array[index].dispose();
  47302. }
  47303. }
  47304. }
  47305. this._textures = {};
  47306. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47307. };
  47308. ShaderMaterial.prototype.serialize = function () {
  47309. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47310. serializationObject.customType = "BABYLON.ShaderMaterial";
  47311. serializationObject.options = this._options;
  47312. serializationObject.shaderPath = this._shaderPath;
  47313. var name;
  47314. // Texture
  47315. serializationObject.textures = {};
  47316. for (name in this._textures) {
  47317. serializationObject.textures[name] = this._textures[name].serialize();
  47318. }
  47319. // Texture arrays
  47320. serializationObject.textureArrays = {};
  47321. for (name in this._textureArrays) {
  47322. serializationObject.textureArrays[name] = [];
  47323. var array = this._textureArrays[name];
  47324. for (var index = 0; index < array.length; index++) {
  47325. serializationObject.textureArrays[name].push(array[index].serialize());
  47326. }
  47327. }
  47328. // Float
  47329. serializationObject.floats = {};
  47330. for (name in this._floats) {
  47331. serializationObject.floats[name] = this._floats[name];
  47332. }
  47333. // Float s
  47334. serializationObject.floatArrays = {};
  47335. for (name in this._floatsArrays) {
  47336. serializationObject.floatArrays[name] = this._floatsArrays[name];
  47337. }
  47338. // Color3
  47339. serializationObject.colors3 = {};
  47340. for (name in this._colors3) {
  47341. serializationObject.colors3[name] = this._colors3[name].asArray();
  47342. }
  47343. // Color4
  47344. serializationObject.colors4 = {};
  47345. for (name in this._colors4) {
  47346. serializationObject.colors4[name] = this._colors4[name].asArray();
  47347. }
  47348. // Vector2
  47349. serializationObject.vectors2 = {};
  47350. for (name in this._vectors2) {
  47351. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47352. }
  47353. // Vector3
  47354. serializationObject.vectors3 = {};
  47355. for (name in this._vectors3) {
  47356. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47357. }
  47358. // Vector4
  47359. serializationObject.vectors4 = {};
  47360. for (name in this._vectors4) {
  47361. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47362. }
  47363. // Matrix
  47364. serializationObject.matrices = {};
  47365. for (name in this._matrices) {
  47366. serializationObject.matrices[name] = this._matrices[name].asArray();
  47367. }
  47368. // Matrix 3x3
  47369. serializationObject.matrices3x3 = {};
  47370. for (name in this._matrices3x3) {
  47371. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47372. }
  47373. // Matrix 2x2
  47374. serializationObject.matrices2x2 = {};
  47375. for (name in this._matrices2x2) {
  47376. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47377. }
  47378. return serializationObject;
  47379. };
  47380. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47381. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47382. var name;
  47383. // Texture
  47384. for (name in source.textures) {
  47385. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47386. }
  47387. // Texture arrays
  47388. for (name in source.textureArrays) {
  47389. var array = source.textureArrays[name];
  47390. var textureArray = new Array();
  47391. for (var index = 0; index < array.length; index++) {
  47392. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47393. }
  47394. material.setTextureArray(name, textureArray);
  47395. }
  47396. // Float
  47397. for (name in source.floats) {
  47398. material.setFloat(name, source.floats[name]);
  47399. }
  47400. // Float s
  47401. for (name in source.floatsArrays) {
  47402. material.setFloats(name, source.floatsArrays[name]);
  47403. }
  47404. // Color3
  47405. for (name in source.colors3) {
  47406. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47407. }
  47408. // Color4
  47409. for (name in source.colors4) {
  47410. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47411. }
  47412. // Vector2
  47413. for (name in source.vectors2) {
  47414. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47415. }
  47416. // Vector3
  47417. for (name in source.vectors3) {
  47418. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47419. }
  47420. // Vector4
  47421. for (name in source.vectors4) {
  47422. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47423. }
  47424. // Matrix
  47425. for (name in source.matrices) {
  47426. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47427. }
  47428. // Matrix 3x3
  47429. for (name in source.matrices3x3) {
  47430. material.setMatrix3x3(name, source.matrices3x3[name]);
  47431. }
  47432. // Matrix 2x2
  47433. for (name in source.matrices2x2) {
  47434. material.setMatrix2x2(name, source.matrices2x2[name]);
  47435. }
  47436. return material;
  47437. };
  47438. return ShaderMaterial;
  47439. })(BABYLON.Material);
  47440. BABYLON.ShaderMaterial = ShaderMaterial;
  47441. })(BABYLON || (BABYLON = {}));
  47442. var BABYLON;
  47443. (function (BABYLON) {
  47444. var Internals;
  47445. (function (Internals) {
  47446. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  47447. // All values and structures referenced from:
  47448. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  47449. var DDS_MAGIC = 0x20534444;
  47450. 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;
  47451. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  47452. 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;
  47453. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  47454. function FourCCToInt32(value) {
  47455. return value.charCodeAt(0) +
  47456. (value.charCodeAt(1) << 8) +
  47457. (value.charCodeAt(2) << 16) +
  47458. (value.charCodeAt(3) << 24);
  47459. }
  47460. function Int32ToFourCC(value) {
  47461. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  47462. }
  47463. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  47464. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  47465. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  47466. var headerLengthInt = 31; // The header length in 32 bit ints
  47467. // Offsets into the header array
  47468. var off_magic = 0;
  47469. var off_size = 1;
  47470. var off_flags = 2;
  47471. var off_height = 3;
  47472. var off_width = 4;
  47473. var off_mipmapCount = 7;
  47474. var off_pfFlags = 20;
  47475. var off_pfFourCC = 21;
  47476. var off_RGBbpp = 22;
  47477. var off_RMask = 23;
  47478. var off_GMask = 24;
  47479. var off_BMask = 25;
  47480. var off_AMask = 26;
  47481. var off_caps1 = 27;
  47482. var off_caps2 = 28;
  47483. ;
  47484. var DDSTools = (function () {
  47485. function DDSTools() {
  47486. }
  47487. DDSTools.GetDDSInfo = function (arrayBuffer) {
  47488. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  47489. var mipmapCount = 1;
  47490. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  47491. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47492. }
  47493. return {
  47494. width: header[off_width],
  47495. height: header[off_height],
  47496. mipmapCount: mipmapCount,
  47497. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  47498. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  47499. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  47500. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  47501. };
  47502. };
  47503. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47504. var byteArray = new Uint8Array(dataLength);
  47505. var srcData = new Uint8Array(arrayBuffer);
  47506. var index = 0;
  47507. for (var y = height - 1; y >= 0; y--) {
  47508. for (var x = 0; x < width; x++) {
  47509. var srcPos = dataOffset + (x + y * width) * 4;
  47510. byteArray[index + 2] = srcData[srcPos];
  47511. byteArray[index + 1] = srcData[srcPos + 1];
  47512. byteArray[index] = srcData[srcPos + 2];
  47513. byteArray[index + 3] = srcData[srcPos + 3];
  47514. index += 4;
  47515. }
  47516. }
  47517. return byteArray;
  47518. };
  47519. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47520. var byteArray = new Uint8Array(dataLength);
  47521. var srcData = new Uint8Array(arrayBuffer);
  47522. var index = 0;
  47523. for (var y = height - 1; y >= 0; y--) {
  47524. for (var x = 0; x < width; x++) {
  47525. var srcPos = dataOffset + (x + y * width) * 3;
  47526. byteArray[index + 2] = srcData[srcPos];
  47527. byteArray[index + 1] = srcData[srcPos + 1];
  47528. byteArray[index] = srcData[srcPos + 2];
  47529. index += 3;
  47530. }
  47531. }
  47532. return byteArray;
  47533. };
  47534. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  47535. var byteArray = new Uint8Array(dataLength);
  47536. var srcData = new Uint8Array(arrayBuffer);
  47537. var index = 0;
  47538. for (var y = height - 1; y >= 0; y--) {
  47539. for (var x = 0; x < width; x++) {
  47540. var srcPos = dataOffset + (x + y * width);
  47541. byteArray[index] = srcData[srcPos];
  47542. index++;
  47543. }
  47544. }
  47545. return byteArray;
  47546. };
  47547. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  47548. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  47549. if (header[off_magic] != DDS_MAGIC) {
  47550. BABYLON.Tools.Error("Invalid magic number in DDS header");
  47551. return;
  47552. }
  47553. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  47554. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  47555. return;
  47556. }
  47557. if (info.isFourCC) {
  47558. fourCC = header[off_pfFourCC];
  47559. switch (fourCC) {
  47560. case FOURCC_DXT1:
  47561. blockBytes = 8;
  47562. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  47563. break;
  47564. case FOURCC_DXT3:
  47565. blockBytes = 16;
  47566. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  47567. break;
  47568. case FOURCC_DXT5:
  47569. blockBytes = 16;
  47570. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  47571. break;
  47572. default:
  47573. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  47574. return;
  47575. }
  47576. }
  47577. mipmapCount = 1;
  47578. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  47579. mipmapCount = Math.max(1, header[off_mipmapCount]);
  47580. }
  47581. var bpp = header[off_RGBbpp];
  47582. for (var face = 0; face < faces; face++) {
  47583. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  47584. width = header[off_width];
  47585. height = header[off_height];
  47586. dataOffset = header[off_size] + 4;
  47587. for (i = 0; i < mipmapCount; ++i) {
  47588. if (info.isRGB) {
  47589. if (bpp === 24) {
  47590. dataLength = width * height * 3;
  47591. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47592. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  47593. }
  47594. else {
  47595. dataLength = width * height * 4;
  47596. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47597. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  47598. }
  47599. }
  47600. else if (info.isLuminance) {
  47601. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  47602. var unpaddedRowSize = width;
  47603. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  47604. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  47605. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  47606. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  47607. }
  47608. else {
  47609. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  47610. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  47611. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  47612. }
  47613. dataOffset += dataLength;
  47614. width *= 0.5;
  47615. height *= 0.5;
  47616. width = Math.max(1.0, width);
  47617. height = Math.max(1.0, height);
  47618. }
  47619. }
  47620. };
  47621. return DDSTools;
  47622. })();
  47623. Internals.DDSTools = DDSTools;
  47624. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47625. })(BABYLON || (BABYLON = {}));
  47626. var BABYLON;
  47627. (function (BABYLON) {
  47628. var CannonJSPlugin = (function () {
  47629. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  47630. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  47631. if (iterations === void 0) { iterations = 10; }
  47632. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  47633. this.name = "CannonJSPlugin";
  47634. this._physicsMaterials = [];
  47635. this._fixedTimeStep = 1 / 60;
  47636. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47637. this._currentCollisionGroup = 2;
  47638. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  47639. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  47640. this._tmpPosition = BABYLON.Vector3.Zero();
  47641. this._tmpQuaternion = new BABYLON.Quaternion();
  47642. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  47643. this._tmpDeltaRotation = new BABYLON.Quaternion();
  47644. this._tmpUnityRotation = new BABYLON.Quaternion();
  47645. if (!this.isSupported()) {
  47646. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  47647. return;
  47648. }
  47649. this.world = new CANNON.World();
  47650. this.world.broadphase = new CANNON.NaiveBroadphase();
  47651. this.world.solver.iterations = iterations;
  47652. }
  47653. CannonJSPlugin.prototype.setGravity = function (gravity) {
  47654. this.world.gravity.copy(gravity);
  47655. };
  47656. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  47657. this._fixedTimeStep = timeStep;
  47658. };
  47659. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  47660. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  47661. };
  47662. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  47663. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47664. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47665. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47666. };
  47667. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  47668. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  47669. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  47670. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  47671. };
  47672. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  47673. //parent-child relationship. Does this impostor has a parent impostor?
  47674. if (impostor.parent) {
  47675. if (impostor.physicsBody) {
  47676. this.removePhysicsBody(impostor);
  47677. //TODO is that needed?
  47678. impostor.forceUpdate();
  47679. }
  47680. return;
  47681. }
  47682. //should a new body be created for this impostor?
  47683. if (impostor.isBodyInitRequired()) {
  47684. var shape = this._createShape(impostor);
  47685. //unregister events, if body is being changed
  47686. var oldBody = impostor.physicsBody;
  47687. if (oldBody) {
  47688. this.removePhysicsBody(impostor);
  47689. }
  47690. //create the body and material
  47691. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  47692. var bodyCreationObject = {
  47693. mass: impostor.getParam("mass"),
  47694. material: material
  47695. };
  47696. // A simple extend, in case native options were used.
  47697. var nativeOptions = impostor.getParam("nativeOptions");
  47698. for (var key in nativeOptions) {
  47699. if (nativeOptions.hasOwnProperty(key)) {
  47700. bodyCreationObject[key] = nativeOptions[key];
  47701. }
  47702. }
  47703. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  47704. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  47705. this.world.addEventListener("preStep", impostor.beforeStep);
  47706. this.world.addEventListener("postStep", impostor.afterStep);
  47707. impostor.physicsBody.addShape(shape);
  47708. this.world.add(impostor.physicsBody);
  47709. //try to keep the body moving in the right direction by taking old properties.
  47710. //Should be tested!
  47711. if (oldBody) {
  47712. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  47713. impostor.physicsBody[param].copy(oldBody[param]);
  47714. });
  47715. }
  47716. this._processChildMeshes(impostor);
  47717. }
  47718. //now update the body's transformation
  47719. this._updatePhysicsBodyTransformation(impostor);
  47720. };
  47721. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  47722. var _this = this;
  47723. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  47724. if (meshChildren.length) {
  47725. var processMesh = function (localPosition, mesh) {
  47726. var childImpostor = mesh.getPhysicsImpostor();
  47727. if (childImpostor) {
  47728. var parent = childImpostor.parent;
  47729. if (parent !== mainImpostor) {
  47730. var localPosition = mesh.position;
  47731. if (childImpostor.physicsBody) {
  47732. _this.removePhysicsBody(childImpostor);
  47733. childImpostor.physicsBody = null;
  47734. }
  47735. childImpostor.parent = mainImpostor;
  47736. childImpostor.resetUpdateFlags();
  47737. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  47738. //Add the mass of the children.
  47739. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  47740. }
  47741. }
  47742. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  47743. };
  47744. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  47745. }
  47746. };
  47747. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  47748. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  47749. this.world.removeEventListener("preStep", impostor.beforeStep);
  47750. this.world.removeEventListener("postStep", impostor.afterStep);
  47751. this.world.remove(impostor.physicsBody);
  47752. };
  47753. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  47754. var mainBody = impostorJoint.mainImpostor.physicsBody;
  47755. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  47756. if (!mainBody || !connectedBody) {
  47757. return;
  47758. }
  47759. var constraint;
  47760. var jointData = impostorJoint.joint.jointData;
  47761. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  47762. var constraintData = {
  47763. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  47764. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  47765. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  47766. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  47767. maxForce: jointData.nativeParams.maxForce,
  47768. collideConnected: !!jointData.collision
  47769. };
  47770. //Not needed, Cannon has a collideConnected flag
  47771. /*if (!jointData.collision) {
  47772. //add 1st body to a collision group of its own, if it is not in 1
  47773. if (mainBody.collisionFilterGroup === 1) {
  47774. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  47775. this._currentCollisionGroup <<= 1;
  47776. }
  47777. if (connectedBody.collisionFilterGroup === 1) {
  47778. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  47779. this._currentCollisionGroup <<= 1;
  47780. }
  47781. //add their mask to the collisionFilterMask of each other:
  47782. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  47783. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  47784. }*/
  47785. switch (impostorJoint.joint.type) {
  47786. case BABYLON.PhysicsJoint.HingeJoint:
  47787. case BABYLON.PhysicsJoint.Hinge2Joint:
  47788. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  47789. break;
  47790. case BABYLON.PhysicsJoint.DistanceJoint:
  47791. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  47792. break;
  47793. case BABYLON.PhysicsJoint.SpringJoint:
  47794. var springData = jointData;
  47795. constraint = new CANNON.Spring(mainBody, connectedBody, {
  47796. restLength: springData.length,
  47797. stiffness: springData.stiffness,
  47798. damping: springData.damping,
  47799. localAnchorA: constraintData.pivotA,
  47800. localAnchorB: constraintData.pivotB
  47801. });
  47802. break;
  47803. case BABYLON.PhysicsJoint.LockJoint:
  47804. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  47805. break;
  47806. case BABYLON.PhysicsJoint.PointToPointJoint:
  47807. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  47808. default:
  47809. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  47810. break;
  47811. }
  47812. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  47813. constraint.collideConnected = !!jointData.collision;
  47814. impostorJoint.joint.physicsJoint = constraint;
  47815. //don't add spring as constraint, as it is not one.
  47816. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  47817. this.world.addConstraint(constraint);
  47818. }
  47819. else {
  47820. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  47821. constraint.applyForce();
  47822. });
  47823. }
  47824. };
  47825. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  47826. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  47827. };
  47828. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  47829. var index;
  47830. var mat;
  47831. for (index = 0; index < this._physicsMaterials.length; index++) {
  47832. mat = this._physicsMaterials[index];
  47833. if (mat.friction === friction && mat.restitution === restitution) {
  47834. return mat;
  47835. }
  47836. }
  47837. var currentMat = new CANNON.Material(name);
  47838. currentMat.friction = friction;
  47839. currentMat.restitution = restitution;
  47840. this._physicsMaterials.push(currentMat);
  47841. return currentMat;
  47842. };
  47843. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  47844. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  47845. };
  47846. CannonJSPlugin.prototype._createShape = function (impostor) {
  47847. var object = impostor.object;
  47848. var returnValue;
  47849. var extendSize = impostor.getObjectExtendSize();
  47850. switch (impostor.type) {
  47851. case BABYLON.PhysicsEngine.SphereImpostor:
  47852. var radiusX = extendSize.x;
  47853. var radiusY = extendSize.y;
  47854. var radiusZ = extendSize.z;
  47855. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  47856. break;
  47857. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  47858. case BABYLON.PhysicsImpostor.CylinderImpostor:
  47859. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  47860. break;
  47861. case BABYLON.PhysicsImpostor.BoxImpostor:
  47862. var box = extendSize.scale(0.5);
  47863. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  47864. break;
  47865. case BABYLON.PhysicsImpostor.PlaneImpostor:
  47866. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  47867. returnValue = new CANNON.Plane();
  47868. break;
  47869. case BABYLON.PhysicsImpostor.MeshImpostor:
  47870. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  47871. var rawFaces = object.getIndices ? object.getIndices() : [];
  47872. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  47873. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  47874. break;
  47875. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  47876. returnValue = this._createHeightmap(object);
  47877. break;
  47878. case BABYLON.PhysicsImpostor.ParticleImpostor:
  47879. returnValue = new CANNON.Particle();
  47880. break;
  47881. }
  47882. return returnValue;
  47883. };
  47884. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  47885. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47886. var matrix = [];
  47887. //For now pointDepth will not be used and will be automatically calculated.
  47888. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  47889. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  47890. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  47891. var elementSize = dim * 2 / arraySize;
  47892. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  47893. for (var i = 0; i < pos.length; i = i + 3) {
  47894. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  47895. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  47896. var y = pos[i + 1] + minY;
  47897. if (!matrix[x]) {
  47898. matrix[x] = [];
  47899. }
  47900. if (!matrix[x][z]) {
  47901. matrix[x][z] = y;
  47902. }
  47903. matrix[x][z] = Math.max(y, matrix[x][z]);
  47904. }
  47905. for (var x = 0; x <= arraySize; ++x) {
  47906. if (!matrix[x]) {
  47907. var loc = 1;
  47908. while (!matrix[(x + loc) % arraySize]) {
  47909. loc++;
  47910. }
  47911. matrix[x] = matrix[(x + loc) % arraySize].slice();
  47912. }
  47913. for (var z = 0; z <= arraySize; ++z) {
  47914. if (!matrix[x][z]) {
  47915. var loc = 1;
  47916. var newValue;
  47917. while (newValue === undefined) {
  47918. newValue = matrix[x][(z + loc++) % arraySize];
  47919. }
  47920. matrix[x][z] = newValue;
  47921. }
  47922. }
  47923. }
  47924. var shape = new CANNON.Heightfield(matrix, {
  47925. elementSize: elementSize
  47926. });
  47927. //For future reference, needed for body transformation
  47928. shape.minY = minY;
  47929. return shape;
  47930. };
  47931. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  47932. var object = impostor.object;
  47933. //make sure it is updated...
  47934. object.computeWorldMatrix && object.computeWorldMatrix(true);
  47935. // The delta between the mesh position and the mesh bounding box center
  47936. var center = impostor.getObjectCenter();
  47937. var extendSize = impostor.getObjectExtendSize();
  47938. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  47939. this._tmpPosition.copyFrom(center);
  47940. var quaternion = object.rotationQuaternion;
  47941. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  47942. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  47943. //-90 DEG in X, precalculated
  47944. quaternion = quaternion.multiply(this._minus90X);
  47945. //Invert! (Precalculated, 90 deg in X)
  47946. //No need to clone. this will never change.
  47947. impostor.setDeltaRotation(this._plus90X);
  47948. }
  47949. //If it is a heightfield, if should be centered.
  47950. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  47951. var mesh = object;
  47952. //calculate the correct body position:
  47953. var rotationQuaternion = mesh.rotationQuaternion;
  47954. mesh.rotationQuaternion = this._tmpUnityRotation;
  47955. mesh.computeWorldMatrix(true);
  47956. //get original center with no rotation
  47957. var c = center.clone();
  47958. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  47959. //rotation is back
  47960. mesh.rotationQuaternion = rotationQuaternion;
  47961. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  47962. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  47963. mesh.setPivotMatrix(p);
  47964. mesh.computeWorldMatrix(true);
  47965. //calculate the translation
  47966. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  47967. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  47968. //add it inverted to the delta
  47969. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  47970. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  47971. mesh.setPivotMatrix(oldPivot);
  47972. mesh.computeWorldMatrix(true);
  47973. }
  47974. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  47975. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  47976. this._tmpPosition.copyFrom(object.position);
  47977. }
  47978. impostor.setDeltaPosition(this._tmpDeltaPosition);
  47979. //Now update the impostor object
  47980. impostor.physicsBody.position.copy(this._tmpPosition);
  47981. impostor.physicsBody.quaternion.copy(quaternion);
  47982. };
  47983. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  47984. impostor.object.position.copyFrom(impostor.physicsBody.position);
  47985. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  47986. };
  47987. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  47988. impostor.physicsBody.position.copy(newPosition);
  47989. impostor.physicsBody.quaternion.copy(newRotation);
  47990. };
  47991. CannonJSPlugin.prototype.isSupported = function () {
  47992. return window.CANNON !== undefined;
  47993. };
  47994. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  47995. impostor.physicsBody.velocity.copy(velocity);
  47996. };
  47997. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  47998. impostor.physicsBody.angularVelocity.copy(velocity);
  47999. };
  48000. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48001. var v = impostor.physicsBody.velocity;
  48002. if (!v)
  48003. return null;
  48004. return new BABYLON.Vector3(v.x, v.y, v.z);
  48005. };
  48006. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48007. var v = impostor.physicsBody.angularVelocity;
  48008. if (!v)
  48009. return null;
  48010. return new BABYLON.Vector3(v.x, v.y, v.z);
  48011. };
  48012. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48013. impostor.physicsBody.mass = mass;
  48014. impostor.physicsBody.updateMassProperties();
  48015. };
  48016. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  48017. impostor.physicsBody.sleep();
  48018. };
  48019. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  48020. impostor.physicsBody.wakeUp();
  48021. };
  48022. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48023. joint.physicsJoint.distance = maxDistance;
  48024. };
  48025. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  48026. if (!motorIndex) {
  48027. joint.physicsJoint.enableMotor();
  48028. }
  48029. };
  48030. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  48031. if (!motorIndex) {
  48032. joint.physicsJoint.disableMotor();
  48033. }
  48034. };
  48035. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48036. if (!motorIndex) {
  48037. joint.physicsJoint.enableMotor();
  48038. joint.physicsJoint.setMotorSpeed(speed);
  48039. if (maxForce) {
  48040. this.setLimit(joint, maxForce);
  48041. }
  48042. }
  48043. };
  48044. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  48045. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  48046. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  48047. };
  48048. CannonJSPlugin.prototype.dispose = function () {
  48049. //nothing to do, actually.
  48050. };
  48051. return CannonJSPlugin;
  48052. })();
  48053. BABYLON.CannonJSPlugin = CannonJSPlugin;
  48054. })(BABYLON || (BABYLON = {}));
  48055. var BABYLON;
  48056. (function (BABYLON) {
  48057. var OimoJSPlugin = (function () {
  48058. function OimoJSPlugin(iterations) {
  48059. this.name = "OimoJSPlugin";
  48060. this._tmpImpostorsArray = [];
  48061. this._tmpPositionVector = BABYLON.Vector3.Zero();
  48062. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  48063. this.world.clear();
  48064. //making sure no stats are calculated
  48065. this.world.isNoStat = true;
  48066. }
  48067. OimoJSPlugin.prototype.setGravity = function (gravity) {
  48068. this.world.gravity.copy(gravity);
  48069. };
  48070. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  48071. this.world.timeStep = timeStep;
  48072. };
  48073. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  48074. var _this = this;
  48075. impostors.forEach(function (impostor) {
  48076. impostor.beforeStep();
  48077. });
  48078. this.world.step();
  48079. impostors.forEach(function (impostor) {
  48080. impostor.afterStep();
  48081. //update the ordered impostors array
  48082. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  48083. });
  48084. //check for collisions
  48085. var contact = this.world.contacts;
  48086. while (contact !== null) {
  48087. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  48088. contact = contact.next;
  48089. continue;
  48090. }
  48091. //is this body colliding with any other? get the impostor
  48092. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  48093. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  48094. if (!mainImpostor || !collidingImpostor) {
  48095. contact = contact.next;
  48096. continue;
  48097. }
  48098. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  48099. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  48100. contact = contact.next;
  48101. }
  48102. };
  48103. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  48104. var mass = impostor.physicsBody.massInfo.mass;
  48105. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  48106. };
  48107. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  48108. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  48109. this.applyImpulse(impostor, force, contactPoint);
  48110. };
  48111. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  48112. var _this = this;
  48113. //parent-child relationship. Does this impostor has a parent impostor?
  48114. if (impostor.parent) {
  48115. if (impostor.physicsBody) {
  48116. this.removePhysicsBody(impostor);
  48117. //TODO is that needed?
  48118. impostor.forceUpdate();
  48119. }
  48120. return;
  48121. }
  48122. if (impostor.isBodyInitRequired()) {
  48123. var bodyConfig = {
  48124. name: impostor.uniqueId,
  48125. //Oimo must have mass, also for static objects.
  48126. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  48127. size: [],
  48128. type: [],
  48129. pos: [],
  48130. rot: [],
  48131. move: impostor.getParam("mass") !== 0,
  48132. //Supporting older versions of Oimo
  48133. world: this.world
  48134. };
  48135. var impostors = [impostor];
  48136. function addToArray(parent) {
  48137. if (!parent.getChildMeshes)
  48138. return;
  48139. parent.getChildMeshes().forEach(function (m) {
  48140. if (m.physicsImpostor) {
  48141. impostors.push(m.physicsImpostor);
  48142. m.physicsImpostor._init();
  48143. }
  48144. });
  48145. }
  48146. addToArray(impostor.object);
  48147. function checkWithEpsilon(value) {
  48148. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  48149. }
  48150. impostors.forEach(function (i) {
  48151. //get the correct bounding box
  48152. var oldQuaternion = i.object.rotationQuaternion;
  48153. var rot = new OIMO.Euler().setFromQuaternion({
  48154. x: impostor.object.rotationQuaternion.x,
  48155. y: impostor.object.rotationQuaternion.y,
  48156. z: impostor.object.rotationQuaternion.z,
  48157. s: impostor.object.rotationQuaternion.w
  48158. });
  48159. var extendSize = i.getObjectExtendSize();
  48160. if (i === impostor) {
  48161. var center = impostor.getObjectCenter();
  48162. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  48163. //Can also use Array.prototype.push.apply
  48164. bodyConfig.pos.push(center.x);
  48165. bodyConfig.pos.push(center.y);
  48166. bodyConfig.pos.push(center.z);
  48167. //tmp solution
  48168. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  48169. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  48170. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  48171. }
  48172. else {
  48173. bodyConfig.pos.push(i.object.position.x);
  48174. bodyConfig.pos.push(i.object.position.y);
  48175. bodyConfig.pos.push(i.object.position.z);
  48176. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  48177. bodyConfig.rot.push(0);
  48178. bodyConfig.rot.push(0);
  48179. bodyConfig.rot.push(0);
  48180. }
  48181. // register mesh
  48182. switch (i.type) {
  48183. case BABYLON.PhysicsImpostor.ParticleImpostor:
  48184. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  48185. case BABYLON.PhysicsImpostor.SphereImpostor:
  48186. var radiusX = extendSize.x;
  48187. var radiusY = extendSize.y;
  48188. var radiusZ = extendSize.z;
  48189. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  48190. bodyConfig.type.push('sphere');
  48191. //due to the way oimo works with compounds, add 3 times
  48192. bodyConfig.size.push(size);
  48193. bodyConfig.size.push(size);
  48194. bodyConfig.size.push(size);
  48195. break;
  48196. case BABYLON.PhysicsImpostor.CylinderImpostor:
  48197. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  48198. var sizeY = checkWithEpsilon(extendSize.y);
  48199. bodyConfig.type.push('cylinder');
  48200. bodyConfig.size.push(sizeX);
  48201. bodyConfig.size.push(sizeY);
  48202. //due to the way oimo works with compounds, add one more value.
  48203. bodyConfig.size.push(sizeY);
  48204. break;
  48205. case BABYLON.PhysicsImpostor.PlaneImpostor:
  48206. case BABYLON.PhysicsImpostor.BoxImpostor:
  48207. default:
  48208. var sizeX = checkWithEpsilon(extendSize.x);
  48209. var sizeY = checkWithEpsilon(extendSize.y);
  48210. var sizeZ = checkWithEpsilon(extendSize.z);
  48211. bodyConfig.type.push('box');
  48212. bodyConfig.size.push(sizeX);
  48213. bodyConfig.size.push(sizeY);
  48214. bodyConfig.size.push(sizeZ);
  48215. break;
  48216. }
  48217. //actually not needed, but hey...
  48218. i.object.rotationQuaternion = oldQuaternion;
  48219. });
  48220. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  48221. }
  48222. else {
  48223. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  48224. }
  48225. impostor.setDeltaPosition(this._tmpPositionVector);
  48226. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  48227. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  48228. };
  48229. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  48230. //impostor.physicsBody.dispose();
  48231. //Same as : (older oimo versions)
  48232. this.world.removeRigidBody(impostor.physicsBody);
  48233. };
  48234. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  48235. var mainBody = impostorJoint.mainImpostor.physicsBody;
  48236. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  48237. if (!mainBody || !connectedBody) {
  48238. return;
  48239. }
  48240. var jointData = impostorJoint.joint.jointData;
  48241. var options = jointData.nativeParams || {};
  48242. var type;
  48243. var nativeJointData = {
  48244. body1: mainBody,
  48245. body2: connectedBody,
  48246. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  48247. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  48248. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  48249. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  48250. min: options.min,
  48251. max: options.max,
  48252. collision: options.collision || jointData.collision,
  48253. spring: options.spring,
  48254. //supporting older version of Oimo
  48255. world: this.world
  48256. };
  48257. switch (impostorJoint.joint.type) {
  48258. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  48259. type = "jointBall";
  48260. break;
  48261. case BABYLON.PhysicsJoint.SpringJoint:
  48262. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  48263. var springData = jointData;
  48264. nativeJointData.min = springData.length || nativeJointData.min;
  48265. //Max should also be set, just make sure it is at least min
  48266. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  48267. case BABYLON.PhysicsJoint.DistanceJoint:
  48268. type = "jointDistance";
  48269. nativeJointData.max = jointData.maxDistance;
  48270. break;
  48271. case BABYLON.PhysicsJoint.PrismaticJoint:
  48272. type = "jointPrisme";
  48273. break;
  48274. case BABYLON.PhysicsJoint.SliderJoint:
  48275. type = "jointSlide";
  48276. break;
  48277. case BABYLON.PhysicsJoint.WheelJoint:
  48278. type = "jointWheel";
  48279. break;
  48280. case BABYLON.PhysicsJoint.HingeJoint:
  48281. default:
  48282. type = "jointHinge";
  48283. break;
  48284. }
  48285. nativeJointData.type = type;
  48286. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  48287. };
  48288. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  48289. //Bug in Oimo prevents us from disposing a joint in the playground
  48290. //joint.joint.physicsJoint.dispose();
  48291. //So we will bruteforce it!
  48292. try {
  48293. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  48294. }
  48295. catch (e) {
  48296. BABYLON.Tools.Warn(e);
  48297. }
  48298. };
  48299. OimoJSPlugin.prototype.isSupported = function () {
  48300. return OIMO !== undefined;
  48301. };
  48302. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  48303. if (!impostor.physicsBody.sleeping) {
  48304. //TODO check that
  48305. if (impostor.physicsBody.shapes.next) {
  48306. var parentShape = this._getLastShape(impostor.physicsBody);
  48307. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  48308. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  48309. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  48310. }
  48311. else {
  48312. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  48313. }
  48314. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  48315. impostor.object.rotationQuaternion.normalize();
  48316. }
  48317. };
  48318. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  48319. var body = impostor.physicsBody;
  48320. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  48321. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  48322. body.syncShapes();
  48323. body.awake();
  48324. };
  48325. OimoJSPlugin.prototype._getLastShape = function (body) {
  48326. var lastShape = body.shapes;
  48327. while (lastShape.next) {
  48328. lastShape = lastShape.next;
  48329. }
  48330. return lastShape;
  48331. };
  48332. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  48333. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  48334. };
  48335. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  48336. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  48337. };
  48338. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  48339. var v = impostor.physicsBody.linearVelocity;
  48340. if (!v)
  48341. return null;
  48342. return new BABYLON.Vector3(v.x, v.y, v.z);
  48343. };
  48344. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  48345. var v = impostor.physicsBody.angularVelocity;
  48346. if (!v)
  48347. return null;
  48348. return new BABYLON.Vector3(v.x, v.y, v.z);
  48349. };
  48350. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  48351. var staticBody = mass === 0;
  48352. //this will actually set the body's density and not its mass.
  48353. //But this is how oimo treats the mass variable.
  48354. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  48355. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  48356. };
  48357. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  48358. impostor.physicsBody.sleep();
  48359. };
  48360. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  48361. impostor.physicsBody.awake();
  48362. };
  48363. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  48364. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  48365. if (minDistance !== void 0) {
  48366. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  48367. }
  48368. };
  48369. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  48370. //TODO separate rotational and transational motors.
  48371. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48372. if (motor) {
  48373. motor.setMotor(speed, maxForce);
  48374. }
  48375. };
  48376. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  48377. //TODO separate rotational and transational motors.
  48378. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  48379. if (motor) {
  48380. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  48381. }
  48382. };
  48383. OimoJSPlugin.prototype.dispose = function () {
  48384. this.world.clear();
  48385. };
  48386. return OimoJSPlugin;
  48387. })();
  48388. BABYLON.OimoJSPlugin = OimoJSPlugin;
  48389. })(BABYLON || (BABYLON = {}));
  48390. var BABYLON;
  48391. (function (BABYLON) {
  48392. var DisplayPassPostProcess = (function (_super) {
  48393. __extends(DisplayPassPostProcess, _super);
  48394. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48395. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  48396. }
  48397. return DisplayPassPostProcess;
  48398. })(BABYLON.PostProcess);
  48399. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48400. })(BABYLON || (BABYLON = {}));
  48401. var BABYLON;
  48402. (function (BABYLON) {
  48403. var SimplificationSettings = (function () {
  48404. function SimplificationSettings(quality, distance, optimizeMesh) {
  48405. this.quality = quality;
  48406. this.distance = distance;
  48407. this.optimizeMesh = optimizeMesh;
  48408. }
  48409. return SimplificationSettings;
  48410. })();
  48411. BABYLON.SimplificationSettings = SimplificationSettings;
  48412. var SimplificationQueue = (function () {
  48413. function SimplificationQueue() {
  48414. this.running = false;
  48415. this._simplificationArray = [];
  48416. }
  48417. SimplificationQueue.prototype.addTask = function (task) {
  48418. this._simplificationArray.push(task);
  48419. };
  48420. SimplificationQueue.prototype.executeNext = function () {
  48421. var task = this._simplificationArray.pop();
  48422. if (task) {
  48423. this.running = true;
  48424. this.runSimplification(task);
  48425. }
  48426. else {
  48427. this.running = false;
  48428. }
  48429. };
  48430. SimplificationQueue.prototype.runSimplification = function (task) {
  48431. var _this = this;
  48432. if (task.parallelProcessing) {
  48433. //parallel simplifier
  48434. task.settings.forEach(function (setting) {
  48435. var simplifier = _this.getSimplifier(task);
  48436. simplifier.simplify(setting, function (newMesh) {
  48437. task.mesh.addLODLevel(setting.distance, newMesh);
  48438. newMesh.isVisible = true;
  48439. //check if it is the last
  48440. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  48441. //all done, run the success callback.
  48442. task.successCallback();
  48443. }
  48444. _this.executeNext();
  48445. });
  48446. });
  48447. }
  48448. else {
  48449. //single simplifier.
  48450. var simplifier = this.getSimplifier(task);
  48451. var runDecimation = function (setting, callback) {
  48452. simplifier.simplify(setting, function (newMesh) {
  48453. task.mesh.addLODLevel(setting.distance, newMesh);
  48454. newMesh.isVisible = true;
  48455. //run the next quality level
  48456. callback();
  48457. });
  48458. };
  48459. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  48460. runDecimation(task.settings[loop.index], function () {
  48461. loop.executeNext();
  48462. });
  48463. }, function () {
  48464. //execution ended, run the success callback.
  48465. if (task.successCallback) {
  48466. task.successCallback();
  48467. }
  48468. _this.executeNext();
  48469. });
  48470. }
  48471. };
  48472. SimplificationQueue.prototype.getSimplifier = function (task) {
  48473. switch (task.simplificationType) {
  48474. case SimplificationType.QUADRATIC:
  48475. default:
  48476. return new QuadraticErrorSimplification(task.mesh);
  48477. }
  48478. };
  48479. return SimplificationQueue;
  48480. })();
  48481. BABYLON.SimplificationQueue = SimplificationQueue;
  48482. /**
  48483. * The implemented types of simplification.
  48484. * At the moment only Quadratic Error Decimation is implemented.
  48485. */
  48486. (function (SimplificationType) {
  48487. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  48488. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  48489. var SimplificationType = BABYLON.SimplificationType;
  48490. var DecimationTriangle = (function () {
  48491. function DecimationTriangle(vertices) {
  48492. this.vertices = vertices;
  48493. this.error = new Array(4);
  48494. this.deleted = false;
  48495. this.isDirty = false;
  48496. this.deletePending = false;
  48497. this.borderFactor = 0;
  48498. }
  48499. return DecimationTriangle;
  48500. })();
  48501. BABYLON.DecimationTriangle = DecimationTriangle;
  48502. var DecimationVertex = (function () {
  48503. function DecimationVertex(position, id) {
  48504. this.position = position;
  48505. this.id = id;
  48506. this.isBorder = true;
  48507. this.q = new QuadraticMatrix();
  48508. this.triangleCount = 0;
  48509. this.triangleStart = 0;
  48510. this.originalOffsets = [];
  48511. }
  48512. DecimationVertex.prototype.updatePosition = function (newPosition) {
  48513. this.position.copyFrom(newPosition);
  48514. };
  48515. return DecimationVertex;
  48516. })();
  48517. BABYLON.DecimationVertex = DecimationVertex;
  48518. var QuadraticMatrix = (function () {
  48519. function QuadraticMatrix(data) {
  48520. this.data = new Array(10);
  48521. for (var i = 0; i < 10; ++i) {
  48522. if (data && data[i]) {
  48523. this.data[i] = data[i];
  48524. }
  48525. else {
  48526. this.data[i] = 0;
  48527. }
  48528. }
  48529. }
  48530. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  48531. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  48532. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  48533. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  48534. return det;
  48535. };
  48536. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  48537. for (var i = 0; i < 10; ++i) {
  48538. this.data[i] += matrix.data[i];
  48539. }
  48540. };
  48541. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  48542. for (var i = 0; i < 10; ++i) {
  48543. this.data[i] += data[i];
  48544. }
  48545. };
  48546. QuadraticMatrix.prototype.add = function (matrix) {
  48547. var m = new QuadraticMatrix();
  48548. for (var i = 0; i < 10; ++i) {
  48549. m.data[i] = this.data[i] + matrix.data[i];
  48550. }
  48551. return m;
  48552. };
  48553. QuadraticMatrix.FromData = function (a, b, c, d) {
  48554. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  48555. };
  48556. //returning an array to avoid garbage collection
  48557. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  48558. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  48559. };
  48560. return QuadraticMatrix;
  48561. })();
  48562. BABYLON.QuadraticMatrix = QuadraticMatrix;
  48563. var Reference = (function () {
  48564. function Reference(vertexId, triangleId) {
  48565. this.vertexId = vertexId;
  48566. this.triangleId = triangleId;
  48567. }
  48568. return Reference;
  48569. })();
  48570. BABYLON.Reference = Reference;
  48571. /**
  48572. * An implementation of the Quadratic Error simplification algorithm.
  48573. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  48574. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  48575. * @author RaananW
  48576. */
  48577. var QuadraticErrorSimplification = (function () {
  48578. function QuadraticErrorSimplification(_mesh) {
  48579. this._mesh = _mesh;
  48580. this.initialized = false;
  48581. this.syncIterations = 5000;
  48582. this.aggressiveness = 7;
  48583. this.decimationIterations = 100;
  48584. this.boundingBoxEpsilon = BABYLON.Epsilon;
  48585. }
  48586. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  48587. var _this = this;
  48588. this.initDecimatedMesh();
  48589. //iterating through the submeshes array, one after the other.
  48590. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  48591. _this.initWithMesh(loop.index, function () {
  48592. _this.runDecimation(settings, loop.index, function () {
  48593. loop.executeNext();
  48594. });
  48595. }, settings.optimizeMesh);
  48596. }, function () {
  48597. setTimeout(function () {
  48598. successCallback(_this._reconstructedMesh);
  48599. }, 0);
  48600. });
  48601. };
  48602. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  48603. var _this = this;
  48604. var gCount = 0;
  48605. triangle.vertices.forEach(function (vertex) {
  48606. var count = 0;
  48607. var vPos = vertex.position;
  48608. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  48609. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  48610. ++count;
  48611. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  48612. ++count;
  48613. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  48614. ++count;
  48615. if (count > 1) {
  48616. ++gCount;
  48617. }
  48618. ;
  48619. });
  48620. if (gCount > 1) {
  48621. console.log(triangle, gCount);
  48622. }
  48623. return gCount > 1;
  48624. };
  48625. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  48626. var _this = this;
  48627. var targetCount = ~~(this.triangles.length * settings.quality);
  48628. var deletedTriangles = 0;
  48629. var triangleCount = this.triangles.length;
  48630. var iterationFunction = function (iteration, callback) {
  48631. setTimeout(function () {
  48632. if (iteration % 5 === 0) {
  48633. _this.updateMesh(iteration === 0);
  48634. }
  48635. for (var i = 0; i < _this.triangles.length; ++i) {
  48636. _this.triangles[i].isDirty = false;
  48637. }
  48638. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  48639. var trianglesIterator = function (i) {
  48640. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  48641. var t = _this.triangles[tIdx];
  48642. if (!t)
  48643. return;
  48644. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  48645. return;
  48646. }
  48647. for (var j = 0; j < 3; ++j) {
  48648. if (t.error[j] < threshold) {
  48649. var deleted0 = [];
  48650. var deleted1 = [];
  48651. var v0 = t.vertices[j];
  48652. var v1 = t.vertices[(j + 1) % 3];
  48653. if (v0.isBorder || v1.isBorder)
  48654. continue;
  48655. var p = BABYLON.Vector3.Zero();
  48656. var n = BABYLON.Vector3.Zero();
  48657. var uv = BABYLON.Vector2.Zero();
  48658. var color = new BABYLON.Color4(0, 0, 0, 1);
  48659. _this.calculateError(v0, v1, p, n, uv, color);
  48660. var delTr = [];
  48661. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  48662. continue;
  48663. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  48664. continue;
  48665. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  48666. continue;
  48667. var uniqueArray = [];
  48668. delTr.forEach(function (deletedT) {
  48669. if (uniqueArray.indexOf(deletedT) === -1) {
  48670. deletedT.deletePending = true;
  48671. uniqueArray.push(deletedT);
  48672. }
  48673. });
  48674. if (uniqueArray.length % 2 !== 0) {
  48675. continue;
  48676. }
  48677. v0.q = v1.q.add(v0.q);
  48678. v0.updatePosition(p);
  48679. var tStart = _this.references.length;
  48680. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  48681. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  48682. var tCount = _this.references.length - tStart;
  48683. if (tCount <= v0.triangleCount) {
  48684. if (tCount) {
  48685. for (var c = 0; c < tCount; c++) {
  48686. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  48687. }
  48688. }
  48689. }
  48690. else {
  48691. v0.triangleStart = tStart;
  48692. }
  48693. v0.triangleCount = tCount;
  48694. break;
  48695. }
  48696. }
  48697. };
  48698. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  48699. }, 0);
  48700. };
  48701. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  48702. if (triangleCount - deletedTriangles <= targetCount)
  48703. loop.breakLoop();
  48704. else {
  48705. iterationFunction(loop.index, function () {
  48706. loop.executeNext();
  48707. });
  48708. }
  48709. }, function () {
  48710. setTimeout(function () {
  48711. //reconstruct this part of the mesh
  48712. _this.reconstructMesh(submeshIndex);
  48713. successCallback();
  48714. }, 0);
  48715. });
  48716. };
  48717. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  48718. var _this = this;
  48719. this.vertices = [];
  48720. this.triangles = [];
  48721. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48722. var indices = this._mesh.getIndices();
  48723. var submesh = this._mesh.subMeshes[submeshIndex];
  48724. var findInVertices = function (positionToSearch) {
  48725. if (optimizeMesh) {
  48726. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  48727. if (_this.vertices[ii].position.equals(positionToSearch)) {
  48728. return _this.vertices[ii];
  48729. }
  48730. }
  48731. }
  48732. return null;
  48733. };
  48734. var vertexReferences = [];
  48735. var vertexInit = function (i) {
  48736. var offset = i + submesh.verticesStart;
  48737. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  48738. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  48739. vertex.originalOffsets.push(offset);
  48740. if (vertex.id === _this.vertices.length) {
  48741. _this.vertices.push(vertex);
  48742. }
  48743. vertexReferences.push(vertex.id);
  48744. };
  48745. //var totalVertices = mesh.getTotalVertices();
  48746. var totalVertices = submesh.verticesCount;
  48747. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  48748. var indicesInit = function (i) {
  48749. var offset = (submesh.indexStart / 3) + i;
  48750. var pos = (offset * 3);
  48751. var i0 = indices[pos + 0];
  48752. var i1 = indices[pos + 1];
  48753. var i2 = indices[pos + 2];
  48754. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  48755. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  48756. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  48757. var triangle = new DecimationTriangle([v0, v1, v2]);
  48758. triangle.originalOffset = pos;
  48759. _this.triangles.push(triangle);
  48760. };
  48761. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  48762. _this.init(callback);
  48763. });
  48764. });
  48765. };
  48766. QuadraticErrorSimplification.prototype.init = function (callback) {
  48767. var _this = this;
  48768. var triangleInit1 = function (i) {
  48769. var t = _this.triangles[i];
  48770. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  48771. for (var j = 0; j < 3; j++) {
  48772. 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))));
  48773. }
  48774. };
  48775. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  48776. var triangleInit2 = function (i) {
  48777. var t = _this.triangles[i];
  48778. for (var j = 0; j < 3; ++j) {
  48779. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  48780. }
  48781. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48782. };
  48783. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  48784. _this.initialized = true;
  48785. callback();
  48786. });
  48787. });
  48788. };
  48789. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  48790. var newTriangles = [];
  48791. var i;
  48792. for (i = 0; i < this.vertices.length; ++i) {
  48793. this.vertices[i].triangleCount = 0;
  48794. }
  48795. var t;
  48796. var j;
  48797. for (i = 0; i < this.triangles.length; ++i) {
  48798. if (!this.triangles[i].deleted) {
  48799. t = this.triangles[i];
  48800. for (j = 0; j < 3; ++j) {
  48801. t.vertices[j].triangleCount = 1;
  48802. }
  48803. newTriangles.push(t);
  48804. }
  48805. }
  48806. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  48807. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  48808. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  48809. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  48810. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48811. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48812. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48813. var vertexCount = 0;
  48814. for (i = 0; i < this.vertices.length; ++i) {
  48815. var vertex = this.vertices[i];
  48816. vertex.id = vertexCount;
  48817. if (vertex.triangleCount) {
  48818. vertex.originalOffsets.forEach(function (originalOffset) {
  48819. newPositionData.push(vertex.position.x);
  48820. newPositionData.push(vertex.position.y);
  48821. newPositionData.push(vertex.position.z);
  48822. newNormalData.push(normalData[originalOffset * 3]);
  48823. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  48824. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  48825. if (uvs && uvs.length) {
  48826. newUVsData.push(uvs[(originalOffset * 2)]);
  48827. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  48828. }
  48829. else if (colorsData && colorsData.length) {
  48830. newColorsData.push(colorsData[(originalOffset * 4)]);
  48831. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  48832. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  48833. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  48834. }
  48835. ++vertexCount;
  48836. });
  48837. }
  48838. }
  48839. var startingIndex = this._reconstructedMesh.getTotalIndices();
  48840. var startingVertex = this._reconstructedMesh.getTotalVertices();
  48841. var submeshesArray = this._reconstructedMesh.subMeshes;
  48842. this._reconstructedMesh.subMeshes = [];
  48843. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  48844. var originalIndices = this._mesh.getIndices();
  48845. for (i = 0; i < newTriangles.length; ++i) {
  48846. t = newTriangles[i]; //now get the new referencing point for each vertex
  48847. [0, 1, 2].forEach(function (idx) {
  48848. var id = originalIndices[t.originalOffset + idx];
  48849. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  48850. if (offset < 0)
  48851. offset = 0;
  48852. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  48853. });
  48854. }
  48855. //overwriting the old vertex buffers and indices.
  48856. this._reconstructedMesh.setIndices(newIndicesArray);
  48857. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  48858. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  48859. if (newUVsData.length > 0)
  48860. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  48861. if (newColorsData.length > 0)
  48862. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  48863. //create submesh
  48864. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  48865. if (submeshIndex > 0) {
  48866. this._reconstructedMesh.subMeshes = [];
  48867. submeshesArray.forEach(function (submesh) {
  48868. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  48869. });
  48870. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  48871. }
  48872. };
  48873. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  48874. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  48875. this._reconstructedMesh.material = this._mesh.material;
  48876. this._reconstructedMesh.parent = this._mesh.parent;
  48877. this._reconstructedMesh.isVisible = false;
  48878. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  48879. };
  48880. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  48881. for (var i = 0; i < vertex1.triangleCount; ++i) {
  48882. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  48883. if (t.deleted)
  48884. continue;
  48885. var s = this.references[vertex1.triangleStart + i].vertexId;
  48886. var v1 = t.vertices[(s + 1) % 3];
  48887. var v2 = t.vertices[(s + 2) % 3];
  48888. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  48889. deletedArray[i] = true;
  48890. delTr.push(t);
  48891. continue;
  48892. }
  48893. var d1 = v1.position.subtract(point);
  48894. d1 = d1.normalize();
  48895. var d2 = v2.position.subtract(point);
  48896. d2 = d2.normalize();
  48897. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  48898. return true;
  48899. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  48900. deletedArray[i] = false;
  48901. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  48902. return true;
  48903. }
  48904. return false;
  48905. };
  48906. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  48907. var newDeleted = deletedTriangles;
  48908. for (var i = 0; i < vertex.triangleCount; ++i) {
  48909. var ref = this.references[vertex.triangleStart + i];
  48910. var t = this.triangles[ref.triangleId];
  48911. if (t.deleted)
  48912. continue;
  48913. if (deletedArray[i] && t.deletePending) {
  48914. t.deleted = true;
  48915. newDeleted++;
  48916. continue;
  48917. }
  48918. t.vertices[ref.vertexId] = origVertex;
  48919. t.isDirty = true;
  48920. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  48921. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  48922. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  48923. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  48924. this.references.push(ref);
  48925. }
  48926. return newDeleted;
  48927. };
  48928. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  48929. for (var i = 0; i < this.vertices.length; ++i) {
  48930. var vCount = [];
  48931. var vId = [];
  48932. var v = this.vertices[i];
  48933. var j;
  48934. for (j = 0; j < v.triangleCount; ++j) {
  48935. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  48936. for (var ii = 0; ii < 3; ii++) {
  48937. var ofs = 0;
  48938. var vv = triangle.vertices[ii];
  48939. while (ofs < vCount.length) {
  48940. if (vId[ofs] === vv.id)
  48941. break;
  48942. ++ofs;
  48943. }
  48944. if (ofs === vCount.length) {
  48945. vCount.push(1);
  48946. vId.push(vv.id);
  48947. }
  48948. else {
  48949. vCount[ofs]++;
  48950. }
  48951. }
  48952. }
  48953. for (j = 0; j < vCount.length; ++j) {
  48954. if (vCount[j] === 1) {
  48955. this.vertices[vId[j]].isBorder = true;
  48956. }
  48957. else {
  48958. this.vertices[vId[j]].isBorder = false;
  48959. }
  48960. }
  48961. }
  48962. };
  48963. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  48964. if (identifyBorders === void 0) { identifyBorders = false; }
  48965. var i;
  48966. if (!identifyBorders) {
  48967. var newTrianglesVector = [];
  48968. for (i = 0; i < this.triangles.length; ++i) {
  48969. if (!this.triangles[i].deleted) {
  48970. newTrianglesVector.push(this.triangles[i]);
  48971. }
  48972. }
  48973. this.triangles = newTrianglesVector;
  48974. }
  48975. for (i = 0; i < this.vertices.length; ++i) {
  48976. this.vertices[i].triangleCount = 0;
  48977. this.vertices[i].triangleStart = 0;
  48978. }
  48979. var t;
  48980. var j;
  48981. var v;
  48982. for (i = 0; i < this.triangles.length; ++i) {
  48983. t = this.triangles[i];
  48984. for (j = 0; j < 3; ++j) {
  48985. v = t.vertices[j];
  48986. v.triangleCount++;
  48987. }
  48988. }
  48989. var tStart = 0;
  48990. for (i = 0; i < this.vertices.length; ++i) {
  48991. this.vertices[i].triangleStart = tStart;
  48992. tStart += this.vertices[i].triangleCount;
  48993. this.vertices[i].triangleCount = 0;
  48994. }
  48995. var newReferences = new Array(this.triangles.length * 3);
  48996. for (i = 0; i < this.triangles.length; ++i) {
  48997. t = this.triangles[i];
  48998. for (j = 0; j < 3; ++j) {
  48999. v = t.vertices[j];
  49000. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  49001. v.triangleCount++;
  49002. }
  49003. }
  49004. this.references = newReferences;
  49005. if (identifyBorders) {
  49006. this.identifyBorder();
  49007. }
  49008. };
  49009. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  49010. var x = point.x;
  49011. var y = point.y;
  49012. var z = point.z;
  49013. 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
  49014. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  49015. };
  49016. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  49017. var q = vertex1.q.add(vertex2.q);
  49018. var border = vertex1.isBorder && vertex2.isBorder;
  49019. var error = 0;
  49020. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  49021. if (qDet !== 0 && !border) {
  49022. if (!pointResult) {
  49023. pointResult = BABYLON.Vector3.Zero();
  49024. }
  49025. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  49026. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  49027. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  49028. error = this.vertexError(q, pointResult);
  49029. }
  49030. else {
  49031. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  49032. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  49033. var error1 = this.vertexError(q, vertex1.position);
  49034. var error2 = this.vertexError(q, vertex2.position);
  49035. var error3 = this.vertexError(q, p3);
  49036. error = Math.min(error1, error2, error3);
  49037. if (error === error1) {
  49038. if (pointResult) {
  49039. pointResult.copyFrom(vertex1.position);
  49040. }
  49041. }
  49042. else if (error === error2) {
  49043. if (pointResult) {
  49044. pointResult.copyFrom(vertex2.position);
  49045. }
  49046. }
  49047. else {
  49048. if (pointResult) {
  49049. pointResult.copyFrom(p3);
  49050. }
  49051. }
  49052. }
  49053. return error;
  49054. };
  49055. return QuadraticErrorSimplification;
  49056. })();
  49057. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  49058. })(BABYLON || (BABYLON = {}));
  49059. var BABYLON;
  49060. (function (BABYLON) {
  49061. var serializedGeometries = [];
  49062. var serializeGeometry = function (geometry, serializationGeometries) {
  49063. if (serializedGeometries[geometry.id]) {
  49064. return;
  49065. }
  49066. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  49067. serializationGeometries.boxes.push(geometry.serialize());
  49068. }
  49069. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  49070. serializationGeometries.spheres.push(geometry.serialize());
  49071. }
  49072. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  49073. serializationGeometries.cylinders.push(geometry.serialize());
  49074. }
  49075. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  49076. serializationGeometries.toruses.push(geometry.serialize());
  49077. }
  49078. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  49079. serializationGeometries.grounds.push(geometry.serialize());
  49080. }
  49081. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  49082. serializationGeometries.planes.push(geometry.serialize());
  49083. }
  49084. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  49085. serializationGeometries.torusKnots.push(geometry.serialize());
  49086. }
  49087. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  49088. throw new Error("Unknown primitive type");
  49089. }
  49090. else {
  49091. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  49092. }
  49093. serializedGeometries[geometry.id] = true;
  49094. };
  49095. var serializeMesh = function (mesh, serializationScene) {
  49096. var serializationObject = {};
  49097. serializationObject.name = mesh.name;
  49098. serializationObject.id = mesh.id;
  49099. if (BABYLON.Tags.HasTags(mesh)) {
  49100. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  49101. }
  49102. serializationObject.position = mesh.position.asArray();
  49103. if (mesh.rotationQuaternion) {
  49104. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  49105. }
  49106. else if (mesh.rotation) {
  49107. serializationObject.rotation = mesh.rotation.asArray();
  49108. }
  49109. serializationObject.scaling = mesh.scaling.asArray();
  49110. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  49111. serializationObject.isEnabled = mesh.isEnabled();
  49112. serializationObject.isVisible = mesh.isVisible;
  49113. serializationObject.infiniteDistance = mesh.infiniteDistance;
  49114. serializationObject.pickable = mesh.isPickable;
  49115. serializationObject.receiveShadows = mesh.receiveShadows;
  49116. serializationObject.billboardMode = mesh.billboardMode;
  49117. serializationObject.visibility = mesh.visibility;
  49118. serializationObject.checkCollisions = mesh.checkCollisions;
  49119. // Parent
  49120. if (mesh.parent) {
  49121. serializationObject.parentId = mesh.parent.id;
  49122. }
  49123. // Geometry
  49124. var geometry = mesh._geometry;
  49125. if (geometry) {
  49126. var geometryId = geometry.id;
  49127. serializationObject.geometryId = geometryId;
  49128. if (!mesh.getScene().getGeometryByID(geometryId)) {
  49129. // 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
  49130. serializeGeometry(geometry, serializationScene.geometries);
  49131. }
  49132. // SubMeshes
  49133. serializationObject.subMeshes = [];
  49134. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49135. var subMesh = mesh.subMeshes[subIndex];
  49136. serializationObject.subMeshes.push({
  49137. materialIndex: subMesh.materialIndex,
  49138. verticesStart: subMesh.verticesStart,
  49139. verticesCount: subMesh.verticesCount,
  49140. indexStart: subMesh.indexStart,
  49141. indexCount: subMesh.indexCount
  49142. });
  49143. }
  49144. }
  49145. // Material
  49146. if (mesh.material) {
  49147. serializationObject.materialId = mesh.material.id;
  49148. }
  49149. else {
  49150. mesh.material = null;
  49151. }
  49152. // Skeleton
  49153. if (mesh.skeleton) {
  49154. serializationObject.skeletonId = mesh.skeleton.id;
  49155. }
  49156. // Physics
  49157. //TODO implement correct serialization for physics impostors.
  49158. if (mesh.getPhysicsImpostor()) {
  49159. serializationObject.physicsMass = mesh.getPhysicsMass();
  49160. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  49161. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  49162. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  49163. }
  49164. // Instances
  49165. serializationObject.instances = [];
  49166. for (var index = 0; index < mesh.instances.length; index++) {
  49167. var instance = mesh.instances[index];
  49168. var serializationInstance = {
  49169. name: instance.name,
  49170. position: instance.position.asArray(),
  49171. scaling: instance.scaling.asArray()
  49172. };
  49173. if (instance.rotationQuaternion) {
  49174. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  49175. }
  49176. else if (instance.rotation) {
  49177. serializationInstance.rotation = instance.rotation.asArray();
  49178. }
  49179. serializationObject.instances.push(serializationInstance);
  49180. // Animations
  49181. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  49182. serializationInstance.ranges = instance.serializeAnimationRanges();
  49183. }
  49184. // Animations
  49185. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  49186. serializationObject.ranges = mesh.serializeAnimationRanges();
  49187. // Layer mask
  49188. serializationObject.layerMask = mesh.layerMask;
  49189. // Action Manager
  49190. if (mesh.actionManager) {
  49191. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  49192. }
  49193. return serializationObject;
  49194. };
  49195. var finalizeSingleMesh = function (mesh, serializationObject) {
  49196. //only works if the mesh is already loaded
  49197. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49198. //serialize material
  49199. if (mesh.material) {
  49200. if (mesh.material instanceof BABYLON.StandardMaterial) {
  49201. serializationObject.materials = serializationObject.materials || [];
  49202. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49203. serializationObject.materials.push(mesh.material.serialize());
  49204. }
  49205. }
  49206. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  49207. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  49208. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  49209. serializationObject.multiMaterials.push(mesh.material.serialize());
  49210. }
  49211. }
  49212. }
  49213. //serialize geometry
  49214. var geometry = mesh._geometry;
  49215. if (geometry) {
  49216. if (!serializationObject.geometries) {
  49217. serializationObject.geometries = {};
  49218. serializationObject.geometries.boxes = [];
  49219. serializationObject.geometries.spheres = [];
  49220. serializationObject.geometries.cylinders = [];
  49221. serializationObject.geometries.toruses = [];
  49222. serializationObject.geometries.grounds = [];
  49223. serializationObject.geometries.planes = [];
  49224. serializationObject.geometries.torusKnots = [];
  49225. serializationObject.geometries.vertexData = [];
  49226. }
  49227. serializeGeometry(geometry, serializationObject.geometries);
  49228. }
  49229. // Skeletons
  49230. if (mesh.skeleton) {
  49231. serializationObject.skeletons = serializationObject.skeletons || [];
  49232. serializationObject.skeletons.push(mesh.skeleton.serialize());
  49233. }
  49234. //serialize the actual mesh
  49235. serializationObject.meshes = serializationObject.meshes || [];
  49236. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49237. }
  49238. };
  49239. var SceneSerializer = (function () {
  49240. function SceneSerializer() {
  49241. }
  49242. SceneSerializer.ClearCache = function () {
  49243. serializedGeometries = [];
  49244. };
  49245. SceneSerializer.Serialize = function (scene) {
  49246. var serializationObject = {};
  49247. // Scene
  49248. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  49249. serializationObject.autoClear = scene.autoClear;
  49250. serializationObject.clearColor = scene.clearColor.asArray();
  49251. serializationObject.ambientColor = scene.ambientColor.asArray();
  49252. serializationObject.gravity = scene.gravity.asArray();
  49253. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  49254. serializationObject.workerCollisions = scene.workerCollisions;
  49255. // Fog
  49256. if (scene.fogMode && scene.fogMode !== 0) {
  49257. serializationObject.fogMode = scene.fogMode;
  49258. serializationObject.fogColor = scene.fogColor.asArray();
  49259. serializationObject.fogStart = scene.fogStart;
  49260. serializationObject.fogEnd = scene.fogEnd;
  49261. serializationObject.fogDensity = scene.fogDensity;
  49262. }
  49263. //Physics
  49264. if (scene.isPhysicsEnabled()) {
  49265. serializationObject.physicsEnabled = true;
  49266. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  49267. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  49268. }
  49269. // Lights
  49270. serializationObject.lights = [];
  49271. var index;
  49272. var light;
  49273. for (index = 0; index < scene.lights.length; index++) {
  49274. light = scene.lights[index];
  49275. serializationObject.lights.push(light.serialize());
  49276. }
  49277. // Cameras
  49278. serializationObject.cameras = [];
  49279. for (index = 0; index < scene.cameras.length; index++) {
  49280. var camera = scene.cameras[index];
  49281. serializationObject.cameras.push(camera.serialize());
  49282. }
  49283. if (scene.activeCamera) {
  49284. serializationObject.activeCameraID = scene.activeCamera.id;
  49285. }
  49286. // Animations
  49287. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  49288. // Materials
  49289. serializationObject.materials = [];
  49290. serializationObject.multiMaterials = [];
  49291. var material;
  49292. for (index = 0; index < scene.materials.length; index++) {
  49293. material = scene.materials[index];
  49294. serializationObject.materials.push(material.serialize());
  49295. }
  49296. // MultiMaterials
  49297. serializationObject.multiMaterials = [];
  49298. for (index = 0; index < scene.multiMaterials.length; index++) {
  49299. var multiMaterial = scene.multiMaterials[index];
  49300. serializationObject.multiMaterials.push(multiMaterial.serialize());
  49301. }
  49302. // Skeletons
  49303. serializationObject.skeletons = [];
  49304. for (index = 0; index < scene.skeletons.length; index++) {
  49305. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  49306. }
  49307. // Geometries
  49308. serializationObject.geometries = {};
  49309. serializationObject.geometries.boxes = [];
  49310. serializationObject.geometries.spheres = [];
  49311. serializationObject.geometries.cylinders = [];
  49312. serializationObject.geometries.toruses = [];
  49313. serializationObject.geometries.grounds = [];
  49314. serializationObject.geometries.planes = [];
  49315. serializationObject.geometries.torusKnots = [];
  49316. serializationObject.geometries.vertexData = [];
  49317. serializedGeometries = [];
  49318. var geometries = scene.getGeometries();
  49319. for (index = 0; index < geometries.length; index++) {
  49320. var geometry = geometries[index];
  49321. if (geometry.isReady()) {
  49322. serializeGeometry(geometry, serializationObject.geometries);
  49323. }
  49324. }
  49325. // Meshes
  49326. serializationObject.meshes = [];
  49327. for (index = 0; index < scene.meshes.length; index++) {
  49328. var abstractMesh = scene.meshes[index];
  49329. if (abstractMesh instanceof BABYLON.Mesh) {
  49330. var mesh = abstractMesh;
  49331. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  49332. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  49333. }
  49334. }
  49335. }
  49336. // Particles Systems
  49337. serializationObject.particleSystems = [];
  49338. for (index = 0; index < scene.particleSystems.length; index++) {
  49339. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  49340. }
  49341. // Lens flares
  49342. serializationObject.lensFlareSystems = [];
  49343. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  49344. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  49345. }
  49346. // Shadows
  49347. serializationObject.shadowGenerators = [];
  49348. for (index = 0; index < scene.lights.length; index++) {
  49349. light = scene.lights[index];
  49350. var shadowGenerator = light.getShadowGenerator();
  49351. // Only support serialization for official generator so far.
  49352. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  49353. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  49354. }
  49355. }
  49356. // Action Manager
  49357. if (scene.actionManager) {
  49358. serializationObject.actions = scene.actionManager.serialize("scene");
  49359. }
  49360. // Audio
  49361. serializationObject.sounds = [];
  49362. for (index = 0; index < scene.soundTracks.length; index++) {
  49363. var soundtrack = scene.soundTracks[index];
  49364. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  49365. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  49366. }
  49367. }
  49368. return serializationObject;
  49369. };
  49370. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  49371. if (withParents === void 0) { withParents = false; }
  49372. if (withChildren === void 0) { withChildren = false; }
  49373. var serializationObject = {};
  49374. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  49375. if (withParents || withChildren) {
  49376. //deliberate for loop! not for each, appended should be processed as well.
  49377. for (var i = 0; i < toSerialize.length; ++i) {
  49378. if (withChildren) {
  49379. toSerialize[i].getDescendants().forEach(function (node) {
  49380. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  49381. toSerialize.push(node);
  49382. }
  49383. });
  49384. }
  49385. //make sure the array doesn't contain the object already
  49386. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  49387. toSerialize.push(toSerialize[i].parent);
  49388. }
  49389. }
  49390. }
  49391. toSerialize.forEach(function (mesh) {
  49392. finalizeSingleMesh(mesh, serializationObject);
  49393. });
  49394. return serializationObject;
  49395. };
  49396. return SceneSerializer;
  49397. })();
  49398. BABYLON.SceneSerializer = SceneSerializer;
  49399. })(BABYLON || (BABYLON = {}));
  49400. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  49401. // Huge respect for a such great lib.
  49402. // Earcut license:
  49403. // Copyright (c) 2016, Mapbox
  49404. //
  49405. // Permission to use, copy, modify, and/or distribute this software for any purpose
  49406. // with or without fee is hereby granted, provided that the above copyright notice
  49407. // and this permission notice appear in all copies.
  49408. //
  49409. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  49410. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49411. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  49412. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  49413. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  49414. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  49415. // THIS SOFTWARE.
  49416. var Earcut;
  49417. (function (Earcut) {
  49418. /**
  49419. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  49420. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  49421. * @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).
  49422. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  49423. */
  49424. function earcut(data, holeIndices, dim) {
  49425. dim = dim || 2;
  49426. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  49427. if (!outerNode)
  49428. return triangles;
  49429. var minX, minY, maxX, maxY, x, y, size;
  49430. if (hasHoles)
  49431. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  49432. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  49433. if (data.length > 80 * dim) {
  49434. minX = maxX = data[0];
  49435. minY = maxY = data[1];
  49436. for (var i = dim; i < outerLen; i += dim) {
  49437. x = data[i];
  49438. y = data[i + 1];
  49439. if (x < minX)
  49440. minX = x;
  49441. if (y < minY)
  49442. minY = y;
  49443. if (x > maxX)
  49444. maxX = x;
  49445. if (y > maxY)
  49446. maxY = y;
  49447. }
  49448. // minX, minY and size are later used to transform coords into integers for z-order calculation
  49449. size = Math.max(maxX - minX, maxY - minY);
  49450. }
  49451. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  49452. return triangles;
  49453. }
  49454. Earcut.earcut = earcut;
  49455. // create a circular doubly linked list from polygon points in the specified winding order
  49456. function linkedList(data, start, end, dim, clockwise) {
  49457. var i, last;
  49458. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  49459. for (i = start; i < end; i += dim)
  49460. last = insertNode(i, data[i], data[i + 1], last);
  49461. }
  49462. else {
  49463. for (i = end - dim; i >= start; i -= dim)
  49464. last = insertNode(i, data[i], data[i + 1], last);
  49465. }
  49466. if (last && equals(last, last.next)) {
  49467. removeNode(last);
  49468. last = last.next;
  49469. }
  49470. return last;
  49471. }
  49472. // eliminate colinear or duplicate points
  49473. function filterPoints(start, end) {
  49474. if (!start)
  49475. return start;
  49476. if (!end)
  49477. end = start;
  49478. var p = start, again;
  49479. do {
  49480. again = false;
  49481. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  49482. removeNode(p);
  49483. p = end = p.prev;
  49484. if (p === p.next)
  49485. return null;
  49486. again = true;
  49487. }
  49488. else {
  49489. p = p.next;
  49490. }
  49491. } while (again || p !== end);
  49492. return end;
  49493. }
  49494. // main ear slicing loop which triangulates a polygon (given as a linked list)
  49495. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  49496. if (!ear)
  49497. return;
  49498. // interlink polygon nodes in z-order
  49499. if (!pass && size)
  49500. indexCurve(ear, minX, minY, size);
  49501. var stop = ear, prev, next;
  49502. // iterate through ears, slicing them one by one
  49503. while (ear.prev !== ear.next) {
  49504. prev = ear.prev;
  49505. next = ear.next;
  49506. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  49507. // cut off the triangle
  49508. triangles.push(prev.i / dim);
  49509. triangles.push(ear.i / dim);
  49510. triangles.push(next.i / dim);
  49511. removeNode(ear);
  49512. // skipping the next vertice leads to less sliver triangles
  49513. ear = next.next;
  49514. stop = next.next;
  49515. continue;
  49516. }
  49517. ear = next;
  49518. // if we looped through the whole remaining polygon and can't find any more ears
  49519. if (ear === stop) {
  49520. // try filtering points and slicing again
  49521. if (!pass) {
  49522. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  49523. }
  49524. else if (pass === 1) {
  49525. ear = cureLocalIntersections(ear, triangles, dim);
  49526. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  49527. }
  49528. else if (pass === 2) {
  49529. splitEarcut(ear, triangles, dim, minX, minY, size);
  49530. }
  49531. break;
  49532. }
  49533. }
  49534. }
  49535. // check whether a polygon node forms a valid ear with adjacent nodes
  49536. function isEar(ear) {
  49537. var a = ear.prev, b = ear, c = ear.next;
  49538. if (area(a, b, c) >= 0)
  49539. return false; // reflex, can't be an ear
  49540. // now make sure we don't have other points inside the potential ear
  49541. var p = ear.next.next;
  49542. while (p !== ear.prev) {
  49543. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49544. area(p.prev, p, p.next) >= 0)
  49545. return false;
  49546. p = p.next;
  49547. }
  49548. return true;
  49549. }
  49550. function isEarHashed(ear, minX, minY, size) {
  49551. var a = ear.prev, b = ear, c = ear.next;
  49552. if (area(a, b, c) >= 0)
  49553. return false; // reflex, can't be an ear
  49554. // triangle bbox; min & max are calculated like this for speed
  49555. 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);
  49556. // z-order range for the current triangle bbox;
  49557. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  49558. // first look for points inside the triangle in increasing z-order
  49559. var p = ear.nextZ;
  49560. while (p && p.z <= maxZ) {
  49561. if (p !== ear.prev &&
  49562. p !== ear.next &&
  49563. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49564. area(p.prev, p, p.next) >= 0)
  49565. return false;
  49566. p = p.nextZ;
  49567. }
  49568. // then look for points in decreasing z-order
  49569. p = ear.prevZ;
  49570. while (p && p.z >= minZ) {
  49571. if (p !== ear.prev &&
  49572. p !== ear.next &&
  49573. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  49574. area(p.prev, p, p.next) >= 0)
  49575. return false;
  49576. p = p.prevZ;
  49577. }
  49578. return true;
  49579. }
  49580. // go through all polygon nodes and cure small local self-intersections
  49581. function cureLocalIntersections(start, triangles, dim) {
  49582. var p = start;
  49583. do {
  49584. var a = p.prev, b = p.next.next;
  49585. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  49586. triangles.push(a.i / dim);
  49587. triangles.push(p.i / dim);
  49588. triangles.push(b.i / dim);
  49589. // remove two nodes involved
  49590. removeNode(p);
  49591. removeNode(p.next);
  49592. p = start = b;
  49593. }
  49594. p = p.next;
  49595. } while (p !== start);
  49596. return p;
  49597. }
  49598. // try splitting polygon into two and triangulate them independently
  49599. function splitEarcut(start, triangles, dim, minX, minY, size) {
  49600. // look for a valid diagonal that divides the polygon into two
  49601. var a = start;
  49602. do {
  49603. var b = a.next.next;
  49604. while (b !== a.prev) {
  49605. if (a.i !== b.i && isValidDiagonal(a, b)) {
  49606. // split the polygon in two by the diagonal
  49607. var c = splitPolygon(a, b);
  49608. // filter colinear points around the cuts
  49609. a = filterPoints(a, a.next);
  49610. c = filterPoints(c, c.next);
  49611. // run earcut on each half
  49612. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  49613. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  49614. return;
  49615. }
  49616. b = b.next;
  49617. }
  49618. a = a.next;
  49619. } while (a !== start);
  49620. }
  49621. // link every hole into the outer loop, producing a single-ring polygon without holes
  49622. function eliminateHoles(data, holeIndices, outerNode, dim) {
  49623. var queue = [], i, len, start, end, list;
  49624. for (i = 0, len = holeIndices.length; i < len; i++) {
  49625. start = holeIndices[i] * dim;
  49626. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49627. list = linkedList(data, start, end, dim, false);
  49628. if (list === list.next)
  49629. list.steiner = true;
  49630. queue.push(getLeftmost(list));
  49631. }
  49632. queue.sort(compareX);
  49633. // process holes from left to right
  49634. for (i = 0; i < queue.length; i++) {
  49635. eliminateHole(queue[i], outerNode);
  49636. outerNode = filterPoints(outerNode, outerNode.next);
  49637. }
  49638. return outerNode;
  49639. }
  49640. function compareX(a, b) {
  49641. return a.x - b.x;
  49642. }
  49643. // find a bridge between vertices that connects hole with an outer ring and and link it
  49644. function eliminateHole(hole, outerNode) {
  49645. outerNode = findHoleBridge(hole, outerNode);
  49646. if (outerNode) {
  49647. var b = splitPolygon(outerNode, hole);
  49648. filterPoints(b, b.next);
  49649. }
  49650. }
  49651. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  49652. function findHoleBridge(hole, outerNode) {
  49653. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  49654. // find a segment intersected by a ray from the hole's leftmost point to the left;
  49655. // segment's endpoint with lesser x will be potential connection point
  49656. do {
  49657. if (hy <= p.y && hy >= p.next.y) {
  49658. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  49659. if (x <= hx && x > qx) {
  49660. qx = x;
  49661. if (x === hx) {
  49662. if (hy === p.y)
  49663. return p;
  49664. if (hy === p.next.y)
  49665. return p.next;
  49666. }
  49667. m = p.x < p.next.x ? p : p.next;
  49668. }
  49669. }
  49670. p = p.next;
  49671. } while (p !== outerNode);
  49672. if (!m)
  49673. return null;
  49674. if (hx === qx)
  49675. return m.prev; // hole touches outer segment; pick lower endpoint
  49676. // look for points inside the triangle of hole point, segment intersection and endpoint;
  49677. // if there are no points found, we have a valid connection;
  49678. // otherwise choose the point of the minimum angle with the ray as connection point
  49679. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  49680. p = m.next;
  49681. while (p !== stop) {
  49682. if (hx >= p.x &&
  49683. p.x >= mx &&
  49684. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  49685. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  49686. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  49687. m = p;
  49688. tanMin = tan;
  49689. }
  49690. }
  49691. p = p.next;
  49692. }
  49693. return m;
  49694. }
  49695. // interlink polygon nodes in z-order
  49696. function indexCurve(start, minX, minY, size) {
  49697. var p = start;
  49698. do {
  49699. if (p.z === null)
  49700. p.z = zOrder(p.x, p.y, minX, minY, size);
  49701. p.prevZ = p.prev;
  49702. p.nextZ = p.next;
  49703. p = p.next;
  49704. } while (p !== start);
  49705. p.prevZ.nextZ = null;
  49706. p.prevZ = null;
  49707. sortLinked(p);
  49708. }
  49709. // Simon Tatham's linked list merge sort algorithm
  49710. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  49711. function sortLinked(list) {
  49712. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  49713. do {
  49714. p = list;
  49715. list = null;
  49716. tail = null;
  49717. numMerges = 0;
  49718. while (p) {
  49719. numMerges++;
  49720. q = p;
  49721. pSize = 0;
  49722. for (i = 0; i < inSize; i++) {
  49723. pSize++;
  49724. q = q.nextZ;
  49725. if (!q)
  49726. break;
  49727. }
  49728. qSize = inSize;
  49729. while (pSize > 0 || (qSize > 0 && q)) {
  49730. if (pSize === 0) {
  49731. e = q;
  49732. q = q.nextZ;
  49733. qSize--;
  49734. }
  49735. else if (qSize === 0 || !q) {
  49736. e = p;
  49737. p = p.nextZ;
  49738. pSize--;
  49739. }
  49740. else if (p.z <= q.z) {
  49741. e = p;
  49742. p = p.nextZ;
  49743. pSize--;
  49744. }
  49745. else {
  49746. e = q;
  49747. q = q.nextZ;
  49748. qSize--;
  49749. }
  49750. if (tail)
  49751. tail.nextZ = e;
  49752. else
  49753. list = e;
  49754. e.prevZ = tail;
  49755. tail = e;
  49756. }
  49757. p = q;
  49758. }
  49759. tail.nextZ = null;
  49760. inSize *= 2;
  49761. } while (numMerges > 1);
  49762. return list;
  49763. }
  49764. // z-order of a point given coords and size of the data bounding box
  49765. function zOrder(x, y, minX, minY, size) {
  49766. // coords are transformed into non-negative 15-bit integer range
  49767. x = 32767 * (x - minX) / size;
  49768. y = 32767 * (y - minY) / size;
  49769. x = (x | (x << 8)) & 0x00FF00FF;
  49770. x = (x | (x << 4)) & 0x0F0F0F0F;
  49771. x = (x | (x << 2)) & 0x33333333;
  49772. x = (x | (x << 1)) & 0x55555555;
  49773. y = (y | (y << 8)) & 0x00FF00FF;
  49774. y = (y | (y << 4)) & 0x0F0F0F0F;
  49775. y = (y | (y << 2)) & 0x33333333;
  49776. y = (y | (y << 1)) & 0x55555555;
  49777. return x | (y << 1);
  49778. }
  49779. // find the leftmost node of a polygon ring
  49780. function getLeftmost(start) {
  49781. var p = start, leftmost = start;
  49782. do {
  49783. if (p.x < leftmost.x)
  49784. leftmost = p;
  49785. p = p.next;
  49786. } while (p !== start);
  49787. return leftmost;
  49788. }
  49789. // check if a point lies within a convex triangle
  49790. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  49791. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  49792. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  49793. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  49794. }
  49795. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  49796. function isValidDiagonal(a, b) {
  49797. return a.next.i !== b.i &&
  49798. a.prev.i !== b.i &&
  49799. !intersectsPolygon(a, b) &&
  49800. locallyInside(a, b) &&
  49801. locallyInside(b, a) &&
  49802. middleInside(a, b);
  49803. }
  49804. // signed area of a triangle
  49805. function area(p, q, r) {
  49806. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  49807. }
  49808. // check if two points are equal
  49809. function equals(p1, p2) {
  49810. return p1.x === p2.x && p1.y === p2.y;
  49811. }
  49812. // check if two segments intersect
  49813. function intersects(p1, q1, p2, q2) {
  49814. if ((equals(p1, q1) && equals(p2, q2)) ||
  49815. (equals(p1, q2) && equals(p2, q1)))
  49816. return true;
  49817. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  49818. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  49819. }
  49820. // check if a polygon diagonal intersects any polygon segments
  49821. function intersectsPolygon(a, b) {
  49822. var p = a;
  49823. do {
  49824. if (p.i !== a.i &&
  49825. p.next.i !== a.i &&
  49826. p.i !== b.i &&
  49827. p.next.i !== b.i &&
  49828. intersects(p, p.next, a, b))
  49829. return true;
  49830. p = p.next;
  49831. } while (p !== a);
  49832. return false;
  49833. }
  49834. // check if a polygon diagonal is locally inside the polygon
  49835. function locallyInside(a, b) {
  49836. return area(a.prev, a, a.next) < 0
  49837. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  49838. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  49839. }
  49840. // check if the middle point of a polygon diagonal is inside the polygon
  49841. function middleInside(a, b) {
  49842. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  49843. do {
  49844. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  49845. inside = !inside;
  49846. p = p.next;
  49847. } while (p !== a);
  49848. return inside;
  49849. }
  49850. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  49851. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  49852. function splitPolygon(a, b) {
  49853. 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;
  49854. a.next = b;
  49855. b.prev = a;
  49856. a2.next = an;
  49857. an.prev = a2;
  49858. b2.next = a2;
  49859. a2.prev = b2;
  49860. bp.next = b2;
  49861. b2.prev = bp;
  49862. return b2;
  49863. }
  49864. // create a node and optionally link it with previous one (in a circular doubly linked list)
  49865. function insertNode(i, x, y, last) {
  49866. var p = new Node(i, x, y);
  49867. if (!last) {
  49868. p.prev = p;
  49869. p.next = p;
  49870. }
  49871. else {
  49872. p.next = last.next;
  49873. p.prev = last;
  49874. last.next.prev = p;
  49875. last.next = p;
  49876. }
  49877. return p;
  49878. }
  49879. function removeNode(p) {
  49880. p.next.prev = p.prev;
  49881. p.prev.next = p.next;
  49882. if (p.prevZ)
  49883. p.prevZ.nextZ = p.nextZ;
  49884. if (p.nextZ)
  49885. p.nextZ.prevZ = p.prevZ;
  49886. }
  49887. function Node(i, x, y) {
  49888. // vertice index in coordinates array
  49889. this.i = i;
  49890. // vertex coordinates
  49891. this.x = x;
  49892. this.y = y;
  49893. // previous and next vertice nodes in a polygon ring
  49894. this.prev = null;
  49895. this.next = null;
  49896. // z-order curve value
  49897. this.z = null;
  49898. // previous and next nodes in z-order
  49899. this.prevZ = null;
  49900. this.nextZ = null;
  49901. // indicates whether this is a steiner point
  49902. this.steiner = false;
  49903. }
  49904. /**
  49905. * return a percentage difference between the polygon area and its triangulation area;
  49906. * used to verify correctness of triangulation
  49907. */
  49908. function deviation(data, holeIndices, dim, triangles) {
  49909. var hasHoles = holeIndices && holeIndices.length;
  49910. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  49911. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  49912. if (hasHoles) {
  49913. for (var i = 0, len = holeIndices.length; i < len; i++) {
  49914. var start = holeIndices[i] * dim;
  49915. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  49916. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  49917. }
  49918. }
  49919. var trianglesArea = 0;
  49920. for (i = 0; i < triangles.length; i += 3) {
  49921. var a = triangles[i] * dim;
  49922. var b = triangles[i + 1] * dim;
  49923. var c = triangles[i + 2] * dim;
  49924. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  49925. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  49926. }
  49927. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  49928. }
  49929. Earcut.deviation = deviation;
  49930. ;
  49931. function signedArea(data, start, end, dim) {
  49932. var sum = 0;
  49933. for (var i = start, j = end - dim; i < end; i += dim) {
  49934. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  49935. j = i;
  49936. }
  49937. return sum;
  49938. }
  49939. /**
  49940. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  49941. */
  49942. function flatten(data) {
  49943. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  49944. for (var i = 0; i < data.length; i++) {
  49945. for (var j = 0; j < data[i].length; j++) {
  49946. for (var d = 0; d < dim; d++)
  49947. result.vertices.push(data[i][j][d]);
  49948. }
  49949. if (i > 0) {
  49950. holeIndex += data[i - 1].length;
  49951. result.holes.push(holeIndex);
  49952. }
  49953. }
  49954. return result;
  49955. }
  49956. Earcut.flatten = flatten;
  49957. ;
  49958. })(Earcut || (Earcut = {}));
  49959. var BABYLON;
  49960. (function (BABYLON) {
  49961. // Unique ID when we import meshes from Babylon to CSG
  49962. var currentCSGMeshId = 0;
  49963. // # class Vertex
  49964. // Represents a vertex of a polygon. Use your own vertex class instead of this
  49965. // one to provide additional features like texture coordinates and vertex
  49966. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  49967. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  49968. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  49969. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  49970. // is not used anywhere else.
  49971. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  49972. var Vertex = (function () {
  49973. function Vertex(pos, normal, uv) {
  49974. this.pos = pos;
  49975. this.normal = normal;
  49976. this.uv = uv;
  49977. }
  49978. Vertex.prototype.clone = function () {
  49979. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  49980. };
  49981. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  49982. // orientation of a polygon is flipped.
  49983. Vertex.prototype.flip = function () {
  49984. this.normal = this.normal.scale(-1);
  49985. };
  49986. // Create a new vertex between this vertex and `other` by linearly
  49987. // interpolating all properties using a parameter of `t`. Subclasses should
  49988. // override this to interpolate additional properties.
  49989. Vertex.prototype.interpolate = function (other, t) {
  49990. 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));
  49991. };
  49992. return Vertex;
  49993. })();
  49994. // # class Plane
  49995. // Represents a plane in 3D space.
  49996. var Plane = (function () {
  49997. function Plane(normal, w) {
  49998. this.normal = normal;
  49999. this.w = w;
  50000. }
  50001. Plane.FromPoints = function (a, b, c) {
  50002. var v0 = c.subtract(a);
  50003. var v1 = b.subtract(a);
  50004. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  50005. return null;
  50006. }
  50007. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  50008. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  50009. };
  50010. Plane.prototype.clone = function () {
  50011. return new Plane(this.normal.clone(), this.w);
  50012. };
  50013. Plane.prototype.flip = function () {
  50014. this.normal.scaleInPlace(-1);
  50015. this.w = -this.w;
  50016. };
  50017. // Split `polygon` by this plane if needed, then put the polygon or polygon
  50018. // fragments in the appropriate lists. Coplanar polygons go into either
  50019. // `coplanarFront` or `coplanarBack` depending on their orientation with
  50020. // respect to this plane. Polygons in front or in back of this plane go into
  50021. // either `front` or `back`.
  50022. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  50023. var COPLANAR = 0;
  50024. var FRONT = 1;
  50025. var BACK = 2;
  50026. var SPANNING = 3;
  50027. // Classify each point as well as the entire polygon into one of the above
  50028. // four classes.
  50029. var polygonType = 0;
  50030. var types = [];
  50031. var i;
  50032. var t;
  50033. for (i = 0; i < polygon.vertices.length; i++) {
  50034. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  50035. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  50036. polygonType |= type;
  50037. types.push(type);
  50038. }
  50039. // Put the polygon in the correct list, splitting it when necessary.
  50040. switch (polygonType) {
  50041. case COPLANAR:
  50042. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  50043. break;
  50044. case FRONT:
  50045. front.push(polygon);
  50046. break;
  50047. case BACK:
  50048. back.push(polygon);
  50049. break;
  50050. case SPANNING:
  50051. var f = [], b = [];
  50052. for (i = 0; i < polygon.vertices.length; i++) {
  50053. var j = (i + 1) % polygon.vertices.length;
  50054. var ti = types[i], tj = types[j];
  50055. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  50056. if (ti !== BACK)
  50057. f.push(vi);
  50058. if (ti !== FRONT)
  50059. b.push(ti !== BACK ? vi.clone() : vi);
  50060. if ((ti | tj) === SPANNING) {
  50061. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  50062. var v = vi.interpolate(vj, t);
  50063. f.push(v);
  50064. b.push(v.clone());
  50065. }
  50066. }
  50067. var poly;
  50068. if (f.length >= 3) {
  50069. poly = new Polygon(f, polygon.shared);
  50070. if (poly.plane)
  50071. front.push(poly);
  50072. }
  50073. if (b.length >= 3) {
  50074. poly = new Polygon(b, polygon.shared);
  50075. if (poly.plane)
  50076. back.push(poly);
  50077. }
  50078. break;
  50079. }
  50080. };
  50081. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  50082. // point is on the plane.
  50083. Plane.EPSILON = 1e-5;
  50084. return Plane;
  50085. })();
  50086. // # class Polygon
  50087. // Represents a convex polygon. The vertices used to initialize a polygon must
  50088. // be coplanar and form a convex loop.
  50089. //
  50090. // Each convex polygon has a `shared` property, which is shared between all
  50091. // polygons that are clones of each other or were split from the same polygon.
  50092. // This can be used to define per-polygon properties (such as surface color).
  50093. var Polygon = (function () {
  50094. function Polygon(vertices, shared) {
  50095. this.vertices = vertices;
  50096. this.shared = shared;
  50097. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  50098. }
  50099. Polygon.prototype.clone = function () {
  50100. var vertices = this.vertices.map(function (v) { return v.clone(); });
  50101. return new Polygon(vertices, this.shared);
  50102. };
  50103. Polygon.prototype.flip = function () {
  50104. this.vertices.reverse().map(function (v) { v.flip(); });
  50105. this.plane.flip();
  50106. };
  50107. return Polygon;
  50108. })();
  50109. // # class Node
  50110. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  50111. // by picking a polygon to split along. That polygon (and all other coplanar
  50112. // polygons) are added directly to that node and the other polygons are added to
  50113. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  50114. // no distinction between internal and leaf nodes.
  50115. var Node = (function () {
  50116. function Node(polygons) {
  50117. this.plane = null;
  50118. this.front = null;
  50119. this.back = null;
  50120. this.polygons = [];
  50121. if (polygons) {
  50122. this.build(polygons);
  50123. }
  50124. }
  50125. Node.prototype.clone = function () {
  50126. var node = new Node();
  50127. node.plane = this.plane && this.plane.clone();
  50128. node.front = this.front && this.front.clone();
  50129. node.back = this.back && this.back.clone();
  50130. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  50131. return node;
  50132. };
  50133. // Convert solid space to empty space and empty space to solid space.
  50134. Node.prototype.invert = function () {
  50135. for (var i = 0; i < this.polygons.length; i++) {
  50136. this.polygons[i].flip();
  50137. }
  50138. if (this.plane) {
  50139. this.plane.flip();
  50140. }
  50141. if (this.front) {
  50142. this.front.invert();
  50143. }
  50144. if (this.back) {
  50145. this.back.invert();
  50146. }
  50147. var temp = this.front;
  50148. this.front = this.back;
  50149. this.back = temp;
  50150. };
  50151. // Recursively remove all polygons in `polygons` that are inside this BSP
  50152. // tree.
  50153. Node.prototype.clipPolygons = function (polygons) {
  50154. if (!this.plane)
  50155. return polygons.slice();
  50156. var front = [], back = [];
  50157. for (var i = 0; i < polygons.length; i++) {
  50158. this.plane.splitPolygon(polygons[i], front, back, front, back);
  50159. }
  50160. if (this.front) {
  50161. front = this.front.clipPolygons(front);
  50162. }
  50163. if (this.back) {
  50164. back = this.back.clipPolygons(back);
  50165. }
  50166. else {
  50167. back = [];
  50168. }
  50169. return front.concat(back);
  50170. };
  50171. // Remove all polygons in this BSP tree that are inside the other BSP tree
  50172. // `bsp`.
  50173. Node.prototype.clipTo = function (bsp) {
  50174. this.polygons = bsp.clipPolygons(this.polygons);
  50175. if (this.front)
  50176. this.front.clipTo(bsp);
  50177. if (this.back)
  50178. this.back.clipTo(bsp);
  50179. };
  50180. // Return a list of all polygons in this BSP tree.
  50181. Node.prototype.allPolygons = function () {
  50182. var polygons = this.polygons.slice();
  50183. if (this.front)
  50184. polygons = polygons.concat(this.front.allPolygons());
  50185. if (this.back)
  50186. polygons = polygons.concat(this.back.allPolygons());
  50187. return polygons;
  50188. };
  50189. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  50190. // new polygons are filtered down to the bottom of the tree and become new
  50191. // nodes there. Each set of polygons is partitioned using the first polygon
  50192. // (no heuristic is used to pick a good split).
  50193. Node.prototype.build = function (polygons) {
  50194. if (!polygons.length)
  50195. return;
  50196. if (!this.plane)
  50197. this.plane = polygons[0].plane.clone();
  50198. var front = [], back = [];
  50199. for (var i = 0; i < polygons.length; i++) {
  50200. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  50201. }
  50202. if (front.length) {
  50203. if (!this.front)
  50204. this.front = new Node();
  50205. this.front.build(front);
  50206. }
  50207. if (back.length) {
  50208. if (!this.back)
  50209. this.back = new Node();
  50210. this.back.build(back);
  50211. }
  50212. };
  50213. return Node;
  50214. })();
  50215. var CSG = (function () {
  50216. function CSG() {
  50217. this.polygons = new Array();
  50218. }
  50219. // Convert BABYLON.Mesh to BABYLON.CSG
  50220. CSG.FromMesh = function (mesh) {
  50221. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  50222. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  50223. if (mesh instanceof BABYLON.Mesh) {
  50224. mesh.computeWorldMatrix(true);
  50225. matrix = mesh.getWorldMatrix();
  50226. meshPosition = mesh.position.clone();
  50227. meshRotation = mesh.rotation.clone();
  50228. if (mesh.rotationQuaternion) {
  50229. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  50230. }
  50231. meshScaling = mesh.scaling.clone();
  50232. }
  50233. else {
  50234. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  50235. }
  50236. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50237. var subMeshes = mesh.subMeshes;
  50238. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  50239. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  50240. vertices = [];
  50241. for (var j = 0; j < 3; j++) {
  50242. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  50243. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  50244. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  50245. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  50246. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  50247. vertex = new Vertex(position, normal, uv);
  50248. vertices.push(vertex);
  50249. }
  50250. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  50251. // To handle the case of degenerated triangle
  50252. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  50253. if (polygon.plane)
  50254. polygons.push(polygon);
  50255. }
  50256. }
  50257. var csg = CSG.FromPolygons(polygons);
  50258. csg.matrix = matrix;
  50259. csg.position = meshPosition;
  50260. csg.rotation = meshRotation;
  50261. csg.scaling = meshScaling;
  50262. csg.rotationQuaternion = meshRotationQuaternion;
  50263. currentCSGMeshId++;
  50264. return csg;
  50265. };
  50266. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  50267. CSG.FromPolygons = function (polygons) {
  50268. var csg = new CSG();
  50269. csg.polygons = polygons;
  50270. return csg;
  50271. };
  50272. CSG.prototype.clone = function () {
  50273. var csg = new CSG();
  50274. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  50275. csg.copyTransformAttributes(this);
  50276. return csg;
  50277. };
  50278. CSG.prototype.toPolygons = function () {
  50279. return this.polygons;
  50280. };
  50281. CSG.prototype.union = function (csg) {
  50282. var a = new Node(this.clone().polygons);
  50283. var b = new Node(csg.clone().polygons);
  50284. a.clipTo(b);
  50285. b.clipTo(a);
  50286. b.invert();
  50287. b.clipTo(a);
  50288. b.invert();
  50289. a.build(b.allPolygons());
  50290. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50291. };
  50292. CSG.prototype.unionInPlace = function (csg) {
  50293. var a = new Node(this.polygons);
  50294. var b = new Node(csg.polygons);
  50295. a.clipTo(b);
  50296. b.clipTo(a);
  50297. b.invert();
  50298. b.clipTo(a);
  50299. b.invert();
  50300. a.build(b.allPolygons());
  50301. this.polygons = a.allPolygons();
  50302. };
  50303. CSG.prototype.subtract = function (csg) {
  50304. var a = new Node(this.clone().polygons);
  50305. var b = new Node(csg.clone().polygons);
  50306. a.invert();
  50307. a.clipTo(b);
  50308. b.clipTo(a);
  50309. b.invert();
  50310. b.clipTo(a);
  50311. b.invert();
  50312. a.build(b.allPolygons());
  50313. a.invert();
  50314. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50315. };
  50316. CSG.prototype.subtractInPlace = function (csg) {
  50317. var a = new Node(this.polygons);
  50318. var b = new Node(csg.polygons);
  50319. a.invert();
  50320. a.clipTo(b);
  50321. b.clipTo(a);
  50322. b.invert();
  50323. b.clipTo(a);
  50324. b.invert();
  50325. a.build(b.allPolygons());
  50326. a.invert();
  50327. this.polygons = a.allPolygons();
  50328. };
  50329. CSG.prototype.intersect = function (csg) {
  50330. var a = new Node(this.clone().polygons);
  50331. var b = new Node(csg.clone().polygons);
  50332. a.invert();
  50333. b.clipTo(a);
  50334. b.invert();
  50335. a.clipTo(b);
  50336. b.clipTo(a);
  50337. a.build(b.allPolygons());
  50338. a.invert();
  50339. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  50340. };
  50341. CSG.prototype.intersectInPlace = function (csg) {
  50342. var a = new Node(this.polygons);
  50343. var b = new Node(csg.polygons);
  50344. a.invert();
  50345. b.clipTo(a);
  50346. b.invert();
  50347. a.clipTo(b);
  50348. b.clipTo(a);
  50349. a.build(b.allPolygons());
  50350. a.invert();
  50351. this.polygons = a.allPolygons();
  50352. };
  50353. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  50354. // not modified.
  50355. CSG.prototype.inverse = function () {
  50356. var csg = this.clone();
  50357. csg.inverseInPlace();
  50358. return csg;
  50359. };
  50360. CSG.prototype.inverseInPlace = function () {
  50361. this.polygons.map(function (p) { p.flip(); });
  50362. };
  50363. // This is used to keep meshes transformations so they can be restored
  50364. // when we build back a Babylon Mesh
  50365. // NB : All CSG operations are performed in world coordinates
  50366. CSG.prototype.copyTransformAttributes = function (csg) {
  50367. this.matrix = csg.matrix;
  50368. this.position = csg.position;
  50369. this.rotation = csg.rotation;
  50370. this.scaling = csg.scaling;
  50371. this.rotationQuaternion = csg.rotationQuaternion;
  50372. return this;
  50373. };
  50374. // Build Raw mesh from CSG
  50375. // Coordinates here are in world space
  50376. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  50377. var matrix = this.matrix.clone();
  50378. matrix.invert();
  50379. 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;
  50380. if (keepSubMeshes) {
  50381. // Sort Polygons, since subMeshes are indices range
  50382. polygons.sort(function (a, b) {
  50383. if (a.shared.meshId === b.shared.meshId) {
  50384. return a.shared.subMeshId - b.shared.subMeshId;
  50385. }
  50386. else {
  50387. return a.shared.meshId - b.shared.meshId;
  50388. }
  50389. });
  50390. }
  50391. for (var i = 0, il = polygons.length; i < il; i++) {
  50392. polygon = polygons[i];
  50393. // Building SubMeshes
  50394. if (!subMesh_dict[polygon.shared.meshId]) {
  50395. subMesh_dict[polygon.shared.meshId] = {};
  50396. }
  50397. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  50398. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  50399. indexStart: +Infinity,
  50400. indexEnd: -Infinity,
  50401. materialIndex: polygon.shared.materialIndex
  50402. };
  50403. }
  50404. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  50405. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  50406. polygonIndices[0] = 0;
  50407. polygonIndices[1] = j - 1;
  50408. polygonIndices[2] = j;
  50409. for (var k = 0; k < 3; k++) {
  50410. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  50411. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  50412. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  50413. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  50414. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  50415. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  50416. // Check if 2 points can be merged
  50417. if (!(typeof vertex_idx !== 'undefined' &&
  50418. normals[vertex_idx * 3] === localNormal.x &&
  50419. normals[vertex_idx * 3 + 1] === localNormal.y &&
  50420. normals[vertex_idx * 3 + 2] === localNormal.z &&
  50421. uvs[vertex_idx * 2] === uv.x &&
  50422. uvs[vertex_idx * 2 + 1] === uv.y)) {
  50423. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  50424. uvs.push(uv.x, uv.y);
  50425. normals.push(normal.x, normal.y, normal.z);
  50426. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  50427. }
  50428. indices.push(vertex_idx);
  50429. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  50430. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  50431. currentIndex++;
  50432. }
  50433. }
  50434. }
  50435. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  50436. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  50437. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  50438. mesh.setIndices(indices);
  50439. if (keepSubMeshes) {
  50440. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  50441. var materialIndexOffset = 0, materialMaxIndex;
  50442. mesh.subMeshes = new Array();
  50443. for (var m in subMesh_dict) {
  50444. materialMaxIndex = -1;
  50445. for (var sm in subMesh_dict[m]) {
  50446. subMesh_obj = subMesh_dict[m][sm];
  50447. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  50448. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  50449. }
  50450. materialIndexOffset += ++materialMaxIndex;
  50451. }
  50452. }
  50453. return mesh;
  50454. };
  50455. // Build Mesh from CSG taking material and transforms into account
  50456. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  50457. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  50458. mesh.material = material;
  50459. mesh.position.copyFrom(this.position);
  50460. mesh.rotation.copyFrom(this.rotation);
  50461. if (this.rotationQuaternion) {
  50462. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  50463. }
  50464. mesh.scaling.copyFrom(this.scaling);
  50465. mesh.computeWorldMatrix(true);
  50466. return mesh;
  50467. };
  50468. return CSG;
  50469. })();
  50470. BABYLON.CSG = CSG;
  50471. })(BABYLON || (BABYLON = {}));
  50472. var BABYLON;
  50473. (function (BABYLON) {
  50474. var VRDistortionCorrectionPostProcess = (function (_super) {
  50475. __extends(VRDistortionCorrectionPostProcess, _super);
  50476. //ANY
  50477. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  50478. var _this = this;
  50479. _super.call(this, name, "vrDistortionCorrection", [
  50480. 'LensCenter',
  50481. 'Scale',
  50482. 'ScaleIn',
  50483. 'HmdWarpParam'
  50484. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  50485. this._isRightEye = isRightEye;
  50486. this._distortionFactors = vrMetrics.distortionK;
  50487. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  50488. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  50489. this.onSizeChangedObservable.add(function () {
  50490. _this.aspectRatio = _this.width * .5 / _this.height;
  50491. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  50492. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  50493. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  50494. });
  50495. this.onApplyObservable.add(function (effect) {
  50496. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  50497. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  50498. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  50499. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  50500. });
  50501. }
  50502. return VRDistortionCorrectionPostProcess;
  50503. })(BABYLON.PostProcess);
  50504. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  50505. })(BABYLON || (BABYLON = {}));
  50506. // Mainly based on these 2 articles :
  50507. // 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
  50508. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  50509. var BABYLON;
  50510. (function (BABYLON) {
  50511. (function (JoystickAxis) {
  50512. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  50513. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  50514. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  50515. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  50516. var JoystickAxis = BABYLON.JoystickAxis;
  50517. var VirtualJoystick = (function () {
  50518. function VirtualJoystick(leftJoystick) {
  50519. var _this = this;
  50520. if (leftJoystick) {
  50521. this._leftJoystick = true;
  50522. }
  50523. else {
  50524. this._leftJoystick = false;
  50525. }
  50526. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  50527. VirtualJoystick._globalJoystickIndex++;
  50528. // By default left & right arrow keys are moving the X
  50529. // and up & down keys are moving the Y
  50530. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50531. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50532. this.reverseLeftRight = false;
  50533. this.reverseUpDown = false;
  50534. // collections of pointers
  50535. this._touches = new BABYLON.StringDictionary();
  50536. this.deltaPosition = BABYLON.Vector3.Zero();
  50537. this._joystickSensibility = 25;
  50538. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50539. this._rotationSpeed = 25;
  50540. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  50541. this._rotateOnAxisRelativeToMesh = false;
  50542. this._onResize = function (evt) {
  50543. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50544. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50545. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  50546. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  50547. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  50548. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  50549. };
  50550. // injecting a canvas element on top of the canvas 3D game
  50551. if (!VirtualJoystick.vjCanvas) {
  50552. window.addEventListener("resize", this._onResize, false);
  50553. VirtualJoystick.vjCanvas = document.createElement("canvas");
  50554. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  50555. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  50556. VirtualJoystick.vjCanvas.width = window.innerWidth;
  50557. VirtualJoystick.vjCanvas.height = window.innerHeight;
  50558. VirtualJoystick.vjCanvas.style.width = "100%";
  50559. VirtualJoystick.vjCanvas.style.height = "100%";
  50560. VirtualJoystick.vjCanvas.style.position = "absolute";
  50561. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  50562. VirtualJoystick.vjCanvas.style.top = "0px";
  50563. VirtualJoystick.vjCanvas.style.left = "0px";
  50564. VirtualJoystick.vjCanvas.style.zIndex = "5";
  50565. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  50566. // Support for jQuery PEP polyfill
  50567. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  50568. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  50569. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  50570. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50571. document.body.appendChild(VirtualJoystick.vjCanvas);
  50572. }
  50573. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  50574. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  50575. this.pressed = false;
  50576. // default joystick color
  50577. this._joystickColor = "cyan";
  50578. this._joystickPointerID = -1;
  50579. // current joystick position
  50580. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  50581. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  50582. // origin joystick position
  50583. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  50584. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  50585. this._onPointerDownHandlerRef = function (evt) {
  50586. _this._onPointerDown(evt);
  50587. };
  50588. this._onPointerMoveHandlerRef = function (evt) {
  50589. _this._onPointerMove(evt);
  50590. };
  50591. this._onPointerOutHandlerRef = function (evt) {
  50592. _this._onPointerUp(evt);
  50593. };
  50594. this._onPointerUpHandlerRef = function (evt) {
  50595. _this._onPointerUp(evt);
  50596. };
  50597. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  50598. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  50599. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  50600. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  50601. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  50602. evt.preventDefault(); // Disables system menu
  50603. }, false);
  50604. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50605. }
  50606. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  50607. this._joystickSensibility = newJoystickSensibility;
  50608. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  50609. };
  50610. VirtualJoystick.prototype._onPointerDown = function (e) {
  50611. var positionOnScreenCondition;
  50612. e.preventDefault();
  50613. if (this._leftJoystick === true) {
  50614. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  50615. }
  50616. else {
  50617. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  50618. }
  50619. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  50620. // First contact will be dedicated to the virtual joystick
  50621. this._joystickPointerID = e.pointerId;
  50622. this._joystickPointerStartPos.x = e.clientX;
  50623. this._joystickPointerStartPos.y = e.clientY;
  50624. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  50625. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  50626. this._deltaJoystickVector.x = 0;
  50627. this._deltaJoystickVector.y = 0;
  50628. this.pressed = true;
  50629. this._touches.add(e.pointerId.toString(), e);
  50630. }
  50631. else {
  50632. // You can only trigger the action buttons with a joystick declared
  50633. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  50634. this._action();
  50635. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  50636. }
  50637. }
  50638. };
  50639. VirtualJoystick.prototype._onPointerMove = function (e) {
  50640. // If the current pointer is the one associated to the joystick (first touch contact)
  50641. if (this._joystickPointerID == e.pointerId) {
  50642. this._joystickPointerPos.x = e.clientX;
  50643. this._joystickPointerPos.y = e.clientY;
  50644. this._deltaJoystickVector = this._joystickPointerPos.clone();
  50645. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  50646. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  50647. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  50648. switch (this._axisTargetedByLeftAndRight) {
  50649. case JoystickAxis.X:
  50650. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  50651. break;
  50652. case JoystickAxis.Y:
  50653. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  50654. break;
  50655. case JoystickAxis.Z:
  50656. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  50657. break;
  50658. }
  50659. var directionUpDown = this.reverseUpDown ? 1 : -1;
  50660. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  50661. switch (this._axisTargetedByUpAndDown) {
  50662. case JoystickAxis.X:
  50663. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  50664. break;
  50665. case JoystickAxis.Y:
  50666. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  50667. break;
  50668. case JoystickAxis.Z:
  50669. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  50670. break;
  50671. }
  50672. }
  50673. else {
  50674. var data = this._touches.get(e.pointerId.toString());
  50675. if (data) {
  50676. data.x = e.clientX;
  50677. data.y = e.clientY;
  50678. }
  50679. }
  50680. };
  50681. VirtualJoystick.prototype._onPointerUp = function (e) {
  50682. if (this._joystickPointerID == e.pointerId) {
  50683. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  50684. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  50685. this._joystickPointerID = -1;
  50686. this.pressed = false;
  50687. }
  50688. else {
  50689. var touch = this._touches.get(e.pointerId.toString());
  50690. if (touch) {
  50691. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50692. }
  50693. }
  50694. this._deltaJoystickVector.x = 0;
  50695. this._deltaJoystickVector.y = 0;
  50696. this._touches.remove(e.pointerId.toString());
  50697. };
  50698. /**
  50699. * Change the color of the virtual joystick
  50700. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  50701. */
  50702. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  50703. this._joystickColor = newColor;
  50704. };
  50705. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  50706. this._action = action;
  50707. };
  50708. // Define which axis you'd like to control for left & right
  50709. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  50710. switch (axis) {
  50711. case JoystickAxis.X:
  50712. case JoystickAxis.Y:
  50713. case JoystickAxis.Z:
  50714. this._axisTargetedByLeftAndRight = axis;
  50715. break;
  50716. default:
  50717. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  50718. break;
  50719. }
  50720. };
  50721. // Define which axis you'd like to control for up & down
  50722. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  50723. switch (axis) {
  50724. case JoystickAxis.X:
  50725. case JoystickAxis.Y:
  50726. case JoystickAxis.Z:
  50727. this._axisTargetedByUpAndDown = axis;
  50728. break;
  50729. default:
  50730. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  50731. break;
  50732. }
  50733. };
  50734. VirtualJoystick.prototype._clearCanvas = function () {
  50735. if (this._leftJoystick) {
  50736. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  50737. }
  50738. else {
  50739. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  50740. }
  50741. };
  50742. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  50743. var _this = this;
  50744. if (this.pressed) {
  50745. this._touches.forEach(function (touch) {
  50746. if (touch.pointerId === _this._joystickPointerID) {
  50747. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  50748. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  50749. VirtualJoystick.vjCanvasContext.beginPath();
  50750. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50751. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50752. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  50753. VirtualJoystick.vjCanvasContext.stroke();
  50754. VirtualJoystick.vjCanvasContext.closePath();
  50755. VirtualJoystick.vjCanvasContext.beginPath();
  50756. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50757. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  50758. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  50759. VirtualJoystick.vjCanvasContext.stroke();
  50760. VirtualJoystick.vjCanvasContext.closePath();
  50761. VirtualJoystick.vjCanvasContext.beginPath();
  50762. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  50763. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  50764. VirtualJoystick.vjCanvasContext.stroke();
  50765. VirtualJoystick.vjCanvasContext.closePath();
  50766. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  50767. }
  50768. else {
  50769. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  50770. VirtualJoystick.vjCanvasContext.beginPath();
  50771. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  50772. VirtualJoystick.vjCanvasContext.beginPath();
  50773. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  50774. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  50775. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  50776. VirtualJoystick.vjCanvasContext.stroke();
  50777. VirtualJoystick.vjCanvasContext.closePath();
  50778. touch.prevX = touch.x;
  50779. touch.prevY = touch.y;
  50780. }
  50781. ;
  50782. });
  50783. }
  50784. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  50785. };
  50786. VirtualJoystick.prototype.releaseCanvas = function () {
  50787. if (VirtualJoystick.vjCanvas) {
  50788. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  50789. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  50790. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  50791. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  50792. window.removeEventListener("resize", this._onResize);
  50793. document.body.removeChild(VirtualJoystick.vjCanvas);
  50794. VirtualJoystick.vjCanvas = null;
  50795. }
  50796. };
  50797. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  50798. VirtualJoystick._globalJoystickIndex = 0;
  50799. return VirtualJoystick;
  50800. })();
  50801. BABYLON.VirtualJoystick = VirtualJoystick;
  50802. })(BABYLON || (BABYLON = {}));
  50803. var BABYLON;
  50804. (function (BABYLON) {
  50805. // We're mainly based on the logic defined into the FreeCamera code
  50806. var VirtualJoysticksCamera = (function (_super) {
  50807. __extends(VirtualJoysticksCamera, _super);
  50808. function VirtualJoysticksCamera(name, position, scene) {
  50809. _super.call(this, name, position, scene);
  50810. this.inputs.addVirtualJoystick();
  50811. }
  50812. return VirtualJoysticksCamera;
  50813. })(BABYLON.FreeCamera);
  50814. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  50815. })(BABYLON || (BABYLON = {}));
  50816. var BABYLON;
  50817. (function (BABYLON) {
  50818. var FreeCameraVirtualJoystickInput = (function () {
  50819. function FreeCameraVirtualJoystickInput() {
  50820. }
  50821. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  50822. return this._leftjoystick;
  50823. };
  50824. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  50825. return this._rightjoystick;
  50826. };
  50827. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  50828. if (this._leftjoystick) {
  50829. var camera = this.camera;
  50830. var speed = camera._computeLocalCameraSpeed() * 50;
  50831. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  50832. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  50833. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  50834. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  50835. if (!this._leftjoystick.pressed) {
  50836. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  50837. }
  50838. if (!this._rightjoystick.pressed) {
  50839. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  50840. }
  50841. }
  50842. };
  50843. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  50844. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  50845. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  50846. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  50847. this._leftjoystick.setJoystickSensibility(0.15);
  50848. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  50849. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  50850. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  50851. this._rightjoystick.reverseUpDown = true;
  50852. this._rightjoystick.setJoystickSensibility(0.05);
  50853. this._rightjoystick.setJoystickColor("yellow");
  50854. };
  50855. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  50856. this._leftjoystick.releaseCanvas();
  50857. this._rightjoystick.releaseCanvas();
  50858. };
  50859. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  50860. return "FreeCameraVirtualJoystickInput";
  50861. };
  50862. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  50863. return "virtualJoystick";
  50864. };
  50865. return FreeCameraVirtualJoystickInput;
  50866. })();
  50867. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  50868. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  50869. })(BABYLON || (BABYLON = {}));
  50870. var BABYLON;
  50871. (function (BABYLON) {
  50872. var AnaglyphPostProcess = (function (_super) {
  50873. __extends(AnaglyphPostProcess, _super);
  50874. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  50875. var _this = this;
  50876. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  50877. this._passedProcess = rigCameras[0]._rigPostProcess;
  50878. this.onApplyObservable.add(function (effect) {
  50879. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  50880. });
  50881. }
  50882. return AnaglyphPostProcess;
  50883. })(BABYLON.PostProcess);
  50884. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  50885. })(BABYLON || (BABYLON = {}));
  50886. var BABYLON;
  50887. (function (BABYLON) {
  50888. var OutlineRenderer = (function () {
  50889. function OutlineRenderer(scene) {
  50890. this._scene = scene;
  50891. }
  50892. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  50893. var _this = this;
  50894. if (useOverlay === void 0) { useOverlay = false; }
  50895. var scene = this._scene;
  50896. var engine = this._scene.getEngine();
  50897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  50898. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  50899. return;
  50900. }
  50901. var mesh = subMesh.getRenderingMesh();
  50902. var material = subMesh.getMaterial();
  50903. engine.enableEffect(this._effect);
  50904. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  50905. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  50906. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50907. // Bones
  50908. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50909. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50910. }
  50911. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  50912. // Alpha test
  50913. if (material && material.needAlphaTesting()) {
  50914. var alphaTexture = material.getAlphaTestTexture();
  50915. this._effect.setTexture("diffuseSampler", alphaTexture);
  50916. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50917. }
  50918. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  50919. };
  50920. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  50921. var defines = [];
  50922. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50923. var mesh = subMesh.getMesh();
  50924. var material = subMesh.getMaterial();
  50925. // Alpha test
  50926. if (material && material.needAlphaTesting()) {
  50927. defines.push("#define ALPHATEST");
  50928. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50929. attribs.push(BABYLON.VertexBuffer.UVKind);
  50930. defines.push("#define UV1");
  50931. }
  50932. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50933. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50934. defines.push("#define UV2");
  50935. }
  50936. }
  50937. // Bones
  50938. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50939. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50940. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50941. if (mesh.numBoneInfluencers > 4) {
  50942. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50943. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50944. }
  50945. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50946. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50947. }
  50948. else {
  50949. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50950. }
  50951. // Instances
  50952. if (useInstances) {
  50953. defines.push("#define INSTANCES");
  50954. attribs.push("world0");
  50955. attribs.push("world1");
  50956. attribs.push("world2");
  50957. attribs.push("world3");
  50958. }
  50959. // Get correct effect
  50960. var join = defines.join("\n");
  50961. if (this._cachedDefines !== join) {
  50962. this._cachedDefines = join;
  50963. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  50964. }
  50965. return this._effect.isReady();
  50966. };
  50967. return OutlineRenderer;
  50968. })();
  50969. BABYLON.OutlineRenderer = OutlineRenderer;
  50970. })(BABYLON || (BABYLON = {}));
  50971. var BABYLON;
  50972. (function (BABYLON) {
  50973. var MeshAssetTask = (function () {
  50974. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  50975. this.name = name;
  50976. this.meshesNames = meshesNames;
  50977. this.rootUrl = rootUrl;
  50978. this.sceneFilename = sceneFilename;
  50979. this.isCompleted = false;
  50980. }
  50981. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  50982. var _this = this;
  50983. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  50984. _this.loadedMeshes = meshes;
  50985. _this.loadedParticleSystems = particleSystems;
  50986. _this.loadedSkeletons = skeletons;
  50987. _this.isCompleted = true;
  50988. if (_this.onSuccess) {
  50989. _this.onSuccess(_this);
  50990. }
  50991. onSuccess();
  50992. }, null, function () {
  50993. if (_this.onError) {
  50994. _this.onError(_this);
  50995. }
  50996. onError();
  50997. });
  50998. };
  50999. return MeshAssetTask;
  51000. })();
  51001. BABYLON.MeshAssetTask = MeshAssetTask;
  51002. var TextFileAssetTask = (function () {
  51003. function TextFileAssetTask(name, url) {
  51004. this.name = name;
  51005. this.url = url;
  51006. this.isCompleted = false;
  51007. }
  51008. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51009. var _this = this;
  51010. BABYLON.Tools.LoadFile(this.url, function (data) {
  51011. _this.text = data;
  51012. _this.isCompleted = true;
  51013. if (_this.onSuccess) {
  51014. _this.onSuccess(_this);
  51015. }
  51016. onSuccess();
  51017. }, null, scene.database, false, function () {
  51018. if (_this.onError) {
  51019. _this.onError(_this);
  51020. }
  51021. onError();
  51022. });
  51023. };
  51024. return TextFileAssetTask;
  51025. })();
  51026. BABYLON.TextFileAssetTask = TextFileAssetTask;
  51027. var BinaryFileAssetTask = (function () {
  51028. function BinaryFileAssetTask(name, url) {
  51029. this.name = name;
  51030. this.url = url;
  51031. this.isCompleted = false;
  51032. }
  51033. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51034. var _this = this;
  51035. BABYLON.Tools.LoadFile(this.url, function (data) {
  51036. _this.data = data;
  51037. _this.isCompleted = true;
  51038. if (_this.onSuccess) {
  51039. _this.onSuccess(_this);
  51040. }
  51041. onSuccess();
  51042. }, null, scene.database, true, function () {
  51043. if (_this.onError) {
  51044. _this.onError(_this);
  51045. }
  51046. onError();
  51047. });
  51048. };
  51049. return BinaryFileAssetTask;
  51050. })();
  51051. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  51052. var ImageAssetTask = (function () {
  51053. function ImageAssetTask(name, url) {
  51054. this.name = name;
  51055. this.url = url;
  51056. this.isCompleted = false;
  51057. }
  51058. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51059. var _this = this;
  51060. var img = new Image();
  51061. img.onload = function () {
  51062. _this.image = img;
  51063. _this.isCompleted = true;
  51064. if (_this.onSuccess) {
  51065. _this.onSuccess(_this);
  51066. }
  51067. onSuccess();
  51068. };
  51069. img.onerror = function () {
  51070. if (_this.onError) {
  51071. _this.onError(_this);
  51072. }
  51073. onError();
  51074. };
  51075. img.src = this.url;
  51076. };
  51077. return ImageAssetTask;
  51078. })();
  51079. BABYLON.ImageAssetTask = ImageAssetTask;
  51080. var TextureAssetTask = (function () {
  51081. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  51082. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51083. this.name = name;
  51084. this.url = url;
  51085. this.noMipmap = noMipmap;
  51086. this.invertY = invertY;
  51087. this.samplingMode = samplingMode;
  51088. this.isCompleted = false;
  51089. }
  51090. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  51091. var _this = this;
  51092. var onload = function () {
  51093. _this.isCompleted = true;
  51094. if (_this.onSuccess) {
  51095. _this.onSuccess(_this);
  51096. }
  51097. onSuccess();
  51098. };
  51099. var onerror = function () {
  51100. if (_this.onError) {
  51101. _this.onError(_this);
  51102. }
  51103. onError();
  51104. };
  51105. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  51106. };
  51107. return TextureAssetTask;
  51108. })();
  51109. BABYLON.TextureAssetTask = TextureAssetTask;
  51110. var AssetsManager = (function () {
  51111. function AssetsManager(scene) {
  51112. this._tasks = new Array();
  51113. this._waitingTasksCount = 0;
  51114. this.useDefaultLoadingScreen = true;
  51115. this._scene = scene;
  51116. }
  51117. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  51118. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  51119. this._tasks.push(task);
  51120. return task;
  51121. };
  51122. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  51123. var task = new TextFileAssetTask(taskName, url);
  51124. this._tasks.push(task);
  51125. return task;
  51126. };
  51127. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  51128. var task = new BinaryFileAssetTask(taskName, url);
  51129. this._tasks.push(task);
  51130. return task;
  51131. };
  51132. AssetsManager.prototype.addImageTask = function (taskName, url) {
  51133. var task = new ImageAssetTask(taskName, url);
  51134. this._tasks.push(task);
  51135. return task;
  51136. };
  51137. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  51138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51139. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  51140. this._tasks.push(task);
  51141. return task;
  51142. };
  51143. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  51144. this._waitingTasksCount--;
  51145. if (this._waitingTasksCount === 0) {
  51146. if (this.onFinish) {
  51147. this.onFinish(this._tasks);
  51148. }
  51149. this._scene.getEngine().hideLoadingUI();
  51150. }
  51151. };
  51152. AssetsManager.prototype._runTask = function (task) {
  51153. var _this = this;
  51154. task.run(this._scene, function () {
  51155. if (_this.onTaskSuccess) {
  51156. _this.onTaskSuccess(task);
  51157. }
  51158. _this._decreaseWaitingTasksCount();
  51159. }, function () {
  51160. if (_this.onTaskError) {
  51161. _this.onTaskError(task);
  51162. }
  51163. _this._decreaseWaitingTasksCount();
  51164. });
  51165. };
  51166. AssetsManager.prototype.reset = function () {
  51167. this._tasks = new Array();
  51168. return this;
  51169. };
  51170. AssetsManager.prototype.load = function () {
  51171. this._waitingTasksCount = this._tasks.length;
  51172. if (this._waitingTasksCount === 0) {
  51173. if (this.onFinish) {
  51174. this.onFinish(this._tasks);
  51175. }
  51176. return this;
  51177. }
  51178. if (this.useDefaultLoadingScreen) {
  51179. this._scene.getEngine().displayLoadingUI();
  51180. }
  51181. for (var index = 0; index < this._tasks.length; index++) {
  51182. var task = this._tasks[index];
  51183. this._runTask(task);
  51184. }
  51185. return this;
  51186. };
  51187. return AssetsManager;
  51188. })();
  51189. BABYLON.AssetsManager = AssetsManager;
  51190. })(BABYLON || (BABYLON = {}));
  51191. var BABYLON;
  51192. (function (BABYLON) {
  51193. var VRCameraMetrics = (function () {
  51194. function VRCameraMetrics() {
  51195. this.compensateDistortion = true;
  51196. }
  51197. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  51198. get: function () {
  51199. return this.hResolution / (2 * this.vResolution);
  51200. },
  51201. enumerable: true,
  51202. configurable: true
  51203. });
  51204. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  51205. get: function () {
  51206. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  51207. },
  51208. enumerable: true,
  51209. configurable: true
  51210. });
  51211. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  51212. get: function () {
  51213. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51214. var h = (4 * meters) / this.hScreenSize;
  51215. return BABYLON.Matrix.Translation(h, 0, 0);
  51216. },
  51217. enumerable: true,
  51218. configurable: true
  51219. });
  51220. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  51221. get: function () {
  51222. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  51223. var h = (4 * meters) / this.hScreenSize;
  51224. return BABYLON.Matrix.Translation(-h, 0, 0);
  51225. },
  51226. enumerable: true,
  51227. configurable: true
  51228. });
  51229. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  51230. get: function () {
  51231. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  51232. },
  51233. enumerable: true,
  51234. configurable: true
  51235. });
  51236. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  51237. get: function () {
  51238. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  51239. },
  51240. enumerable: true,
  51241. configurable: true
  51242. });
  51243. VRCameraMetrics.GetDefault = function () {
  51244. var result = new VRCameraMetrics();
  51245. result.hResolution = 1280;
  51246. result.vResolution = 800;
  51247. result.hScreenSize = 0.149759993;
  51248. result.vScreenSize = 0.0935999975;
  51249. result.vScreenCenter = 0.0467999987,
  51250. result.eyeToScreenDistance = 0.0410000011;
  51251. result.lensSeparationDistance = 0.0635000020;
  51252. result.interpupillaryDistance = 0.0640000030;
  51253. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  51254. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  51255. result.postProcessScaleFactor = 1.714605507808412;
  51256. result.lensCenterOffset = 0.151976421;
  51257. return result;
  51258. };
  51259. return VRCameraMetrics;
  51260. })();
  51261. BABYLON.VRCameraMetrics = VRCameraMetrics;
  51262. })(BABYLON || (BABYLON = {}));
  51263. var BABYLON;
  51264. (function (BABYLON) {
  51265. var VRDeviceOrientationFreeCamera = (function (_super) {
  51266. __extends(VRDeviceOrientationFreeCamera, _super);
  51267. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  51268. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51269. _super.call(this, name, position, scene);
  51270. this.rotationQuaternion = new BABYLON.Quaternion();
  51271. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51272. metrics.compensateDistortion = compensateDistortion;
  51273. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51274. this.inputs.addDeviceOrientation();
  51275. }
  51276. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  51277. return "VRDeviceOrientationFreeCamera";
  51278. };
  51279. return VRDeviceOrientationFreeCamera;
  51280. })(BABYLON.FreeCamera);
  51281. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  51282. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  51283. __extends(VRDeviceOrientationArcRotateCamera, _super);
  51284. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  51285. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51286. _super.call(this, name, alpha, beta, radius, target, scene);
  51287. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51288. metrics.compensateDistortion = compensateDistortion;
  51289. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51290. this.inputs.addVRDeviceOrientation();
  51291. }
  51292. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  51293. return "VRDeviceOrientationArcRotateCamera";
  51294. };
  51295. return VRDeviceOrientationArcRotateCamera;
  51296. })(BABYLON.ArcRotateCamera);
  51297. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  51298. })(BABYLON || (BABYLON = {}));
  51299. var BABYLON;
  51300. (function (BABYLON) {
  51301. var WebVRFreeCamera = (function (_super) {
  51302. __extends(WebVRFreeCamera, _super);
  51303. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  51304. if (compensateDistortion === void 0) { compensateDistortion = true; }
  51305. _super.call(this, name, position, scene);
  51306. this._hmdDevice = null;
  51307. this._sensorDevice = null;
  51308. this._cacheState = null;
  51309. this._vrEnabled = false;
  51310. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  51311. metrics.compensateDistortion = compensateDistortion;
  51312. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  51313. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  51314. this.rotationQuaternion = new BABYLON.Quaternion();
  51315. }
  51316. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  51317. var size = devices.length;
  51318. var i = 0;
  51319. // Reset devices.
  51320. this._sensorDevice = null;
  51321. this._hmdDevice = null;
  51322. // Search for a HmdDevice.
  51323. while (i < size && this._hmdDevice === null) {
  51324. if (devices[i] instanceof HMDVRDevice) {
  51325. this._hmdDevice = devices[i];
  51326. }
  51327. i++;
  51328. }
  51329. i = 0;
  51330. while (i < size && this._sensorDevice === null) {
  51331. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  51332. this._sensorDevice = devices[i];
  51333. }
  51334. i++;
  51335. }
  51336. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  51337. };
  51338. WebVRFreeCamera.prototype._checkInputs = function () {
  51339. if (this._vrEnabled) {
  51340. this._cacheState = this._sensorDevice.getState();
  51341. this.rotationQuaternion.copyFrom(this._cacheState.orientation);
  51342. //Flip in XY plane
  51343. this.rotationQuaternion.z *= -1;
  51344. this.rotationQuaternion.w *= -1;
  51345. }
  51346. _super.prototype._checkInputs.call(this);
  51347. };
  51348. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  51349. _super.prototype.attachControl.call(this, element, noPreventDefault);
  51350. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  51351. if (navigator.getVRDevices) {
  51352. navigator.getVRDevices().then(this._getWebVRDevices);
  51353. }
  51354. else if (navigator.mozGetVRDevices) {
  51355. navigator.mozGetVRDevices(this._getWebVRDevices);
  51356. }
  51357. };
  51358. WebVRFreeCamera.prototype.detachControl = function (element) {
  51359. _super.prototype.detachControl.call(this, element);
  51360. this._vrEnabled = false;
  51361. };
  51362. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  51363. if (!this._hmdDevice)
  51364. return;
  51365. this.getEngine().switchFullscreen(requestPointerlock, { vrDisplay: this._hmdDevice });
  51366. };
  51367. WebVRFreeCamera.prototype.getTypeName = function () {
  51368. return "WebVRFreeCamera";
  51369. };
  51370. return WebVRFreeCamera;
  51371. })(BABYLON.FreeCamera);
  51372. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  51373. })(BABYLON || (BABYLON = {}));
  51374. var BABYLON;
  51375. (function (BABYLON) {
  51376. // Standard optimizations
  51377. var SceneOptimization = (function () {
  51378. function SceneOptimization(priority) {
  51379. if (priority === void 0) { priority = 0; }
  51380. this.priority = priority;
  51381. this.apply = function (scene) {
  51382. return true; // Return true if everything that can be done was applied
  51383. };
  51384. }
  51385. return SceneOptimization;
  51386. })();
  51387. BABYLON.SceneOptimization = SceneOptimization;
  51388. var TextureOptimization = (function (_super) {
  51389. __extends(TextureOptimization, _super);
  51390. function TextureOptimization(priority, maximumSize) {
  51391. var _this = this;
  51392. if (priority === void 0) { priority = 0; }
  51393. if (maximumSize === void 0) { maximumSize = 1024; }
  51394. _super.call(this, priority);
  51395. this.priority = priority;
  51396. this.maximumSize = maximumSize;
  51397. this.apply = function (scene) {
  51398. var allDone = true;
  51399. for (var index = 0; index < scene.textures.length; index++) {
  51400. var texture = scene.textures[index];
  51401. if (!texture.canRescale) {
  51402. continue;
  51403. }
  51404. var currentSize = texture.getSize();
  51405. var maxDimension = Math.max(currentSize.width, currentSize.height);
  51406. if (maxDimension > _this.maximumSize) {
  51407. texture.scale(0.5);
  51408. allDone = false;
  51409. }
  51410. }
  51411. return allDone;
  51412. };
  51413. }
  51414. return TextureOptimization;
  51415. })(SceneOptimization);
  51416. BABYLON.TextureOptimization = TextureOptimization;
  51417. var HardwareScalingOptimization = (function (_super) {
  51418. __extends(HardwareScalingOptimization, _super);
  51419. function HardwareScalingOptimization(priority, maximumScale) {
  51420. var _this = this;
  51421. if (priority === void 0) { priority = 0; }
  51422. if (maximumScale === void 0) { maximumScale = 2; }
  51423. _super.call(this, priority);
  51424. this.priority = priority;
  51425. this.maximumScale = maximumScale;
  51426. this._currentScale = 1;
  51427. this.apply = function (scene) {
  51428. _this._currentScale++;
  51429. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  51430. return _this._currentScale >= _this.maximumScale;
  51431. };
  51432. }
  51433. return HardwareScalingOptimization;
  51434. })(SceneOptimization);
  51435. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  51436. var ShadowsOptimization = (function (_super) {
  51437. __extends(ShadowsOptimization, _super);
  51438. function ShadowsOptimization() {
  51439. _super.apply(this, arguments);
  51440. this.apply = function (scene) {
  51441. scene.shadowsEnabled = false;
  51442. return true;
  51443. };
  51444. }
  51445. return ShadowsOptimization;
  51446. })(SceneOptimization);
  51447. BABYLON.ShadowsOptimization = ShadowsOptimization;
  51448. var PostProcessesOptimization = (function (_super) {
  51449. __extends(PostProcessesOptimization, _super);
  51450. function PostProcessesOptimization() {
  51451. _super.apply(this, arguments);
  51452. this.apply = function (scene) {
  51453. scene.postProcessesEnabled = false;
  51454. return true;
  51455. };
  51456. }
  51457. return PostProcessesOptimization;
  51458. })(SceneOptimization);
  51459. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  51460. var LensFlaresOptimization = (function (_super) {
  51461. __extends(LensFlaresOptimization, _super);
  51462. function LensFlaresOptimization() {
  51463. _super.apply(this, arguments);
  51464. this.apply = function (scene) {
  51465. scene.lensFlaresEnabled = false;
  51466. return true;
  51467. };
  51468. }
  51469. return LensFlaresOptimization;
  51470. })(SceneOptimization);
  51471. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  51472. var ParticlesOptimization = (function (_super) {
  51473. __extends(ParticlesOptimization, _super);
  51474. function ParticlesOptimization() {
  51475. _super.apply(this, arguments);
  51476. this.apply = function (scene) {
  51477. scene.particlesEnabled = false;
  51478. return true;
  51479. };
  51480. }
  51481. return ParticlesOptimization;
  51482. })(SceneOptimization);
  51483. BABYLON.ParticlesOptimization = ParticlesOptimization;
  51484. var RenderTargetsOptimization = (function (_super) {
  51485. __extends(RenderTargetsOptimization, _super);
  51486. function RenderTargetsOptimization() {
  51487. _super.apply(this, arguments);
  51488. this.apply = function (scene) {
  51489. scene.renderTargetsEnabled = false;
  51490. return true;
  51491. };
  51492. }
  51493. return RenderTargetsOptimization;
  51494. })(SceneOptimization);
  51495. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  51496. var MergeMeshesOptimization = (function (_super) {
  51497. __extends(MergeMeshesOptimization, _super);
  51498. function MergeMeshesOptimization() {
  51499. var _this = this;
  51500. _super.apply(this, arguments);
  51501. this._canBeMerged = function (abstractMesh) {
  51502. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  51503. return false;
  51504. }
  51505. var mesh = abstractMesh;
  51506. if (!mesh.isVisible || !mesh.isEnabled()) {
  51507. return false;
  51508. }
  51509. if (mesh.instances.length > 0) {
  51510. return false;
  51511. }
  51512. if (mesh.skeleton || mesh.hasLODLevels) {
  51513. return false;
  51514. }
  51515. if (mesh.parent) {
  51516. return false;
  51517. }
  51518. return true;
  51519. };
  51520. this.apply = function (scene, updateSelectionTree) {
  51521. var globalPool = scene.meshes.slice(0);
  51522. var globalLength = globalPool.length;
  51523. for (var index = 0; index < globalLength; index++) {
  51524. var currentPool = new Array();
  51525. var current = globalPool[index];
  51526. // Checks
  51527. if (!_this._canBeMerged(current)) {
  51528. continue;
  51529. }
  51530. currentPool.push(current);
  51531. // Find compatible meshes
  51532. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  51533. var otherMesh = globalPool[subIndex];
  51534. if (!_this._canBeMerged(otherMesh)) {
  51535. continue;
  51536. }
  51537. if (otherMesh.material !== current.material) {
  51538. continue;
  51539. }
  51540. if (otherMesh.checkCollisions !== current.checkCollisions) {
  51541. continue;
  51542. }
  51543. currentPool.push(otherMesh);
  51544. globalLength--;
  51545. globalPool.splice(subIndex, 1);
  51546. subIndex--;
  51547. }
  51548. if (currentPool.length < 2) {
  51549. continue;
  51550. }
  51551. // Merge meshes
  51552. BABYLON.Mesh.MergeMeshes(currentPool);
  51553. }
  51554. if (updateSelectionTree != undefined) {
  51555. if (updateSelectionTree) {
  51556. scene.createOrUpdateSelectionOctree();
  51557. }
  51558. }
  51559. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  51560. scene.createOrUpdateSelectionOctree();
  51561. }
  51562. return true;
  51563. };
  51564. }
  51565. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  51566. get: function () {
  51567. return MergeMeshesOptimization._UpdateSelectionTree;
  51568. },
  51569. set: function (value) {
  51570. MergeMeshesOptimization._UpdateSelectionTree = value;
  51571. },
  51572. enumerable: true,
  51573. configurable: true
  51574. });
  51575. MergeMeshesOptimization._UpdateSelectionTree = false;
  51576. return MergeMeshesOptimization;
  51577. })(SceneOptimization);
  51578. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  51579. // Options
  51580. var SceneOptimizerOptions = (function () {
  51581. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  51582. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  51583. if (trackerDuration === void 0) { trackerDuration = 2000; }
  51584. this.targetFrameRate = targetFrameRate;
  51585. this.trackerDuration = trackerDuration;
  51586. this.optimizations = new Array();
  51587. }
  51588. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  51589. var result = new SceneOptimizerOptions(targetFrameRate);
  51590. var priority = 0;
  51591. result.optimizations.push(new MergeMeshesOptimization(priority));
  51592. result.optimizations.push(new ShadowsOptimization(priority));
  51593. result.optimizations.push(new LensFlaresOptimization(priority));
  51594. // Next priority
  51595. priority++;
  51596. result.optimizations.push(new PostProcessesOptimization(priority));
  51597. result.optimizations.push(new ParticlesOptimization(priority));
  51598. // Next priority
  51599. priority++;
  51600. result.optimizations.push(new TextureOptimization(priority, 1024));
  51601. return result;
  51602. };
  51603. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  51604. var result = new SceneOptimizerOptions(targetFrameRate);
  51605. var priority = 0;
  51606. result.optimizations.push(new MergeMeshesOptimization(priority));
  51607. result.optimizations.push(new ShadowsOptimization(priority));
  51608. result.optimizations.push(new LensFlaresOptimization(priority));
  51609. // Next priority
  51610. priority++;
  51611. result.optimizations.push(new PostProcessesOptimization(priority));
  51612. result.optimizations.push(new ParticlesOptimization(priority));
  51613. // Next priority
  51614. priority++;
  51615. result.optimizations.push(new TextureOptimization(priority, 512));
  51616. // Next priority
  51617. priority++;
  51618. result.optimizations.push(new RenderTargetsOptimization(priority));
  51619. // Next priority
  51620. priority++;
  51621. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  51622. return result;
  51623. };
  51624. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  51625. var result = new SceneOptimizerOptions(targetFrameRate);
  51626. var priority = 0;
  51627. result.optimizations.push(new MergeMeshesOptimization(priority));
  51628. result.optimizations.push(new ShadowsOptimization(priority));
  51629. result.optimizations.push(new LensFlaresOptimization(priority));
  51630. // Next priority
  51631. priority++;
  51632. result.optimizations.push(new PostProcessesOptimization(priority));
  51633. result.optimizations.push(new ParticlesOptimization(priority));
  51634. // Next priority
  51635. priority++;
  51636. result.optimizations.push(new TextureOptimization(priority, 256));
  51637. // Next priority
  51638. priority++;
  51639. result.optimizations.push(new RenderTargetsOptimization(priority));
  51640. // Next priority
  51641. priority++;
  51642. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  51643. return result;
  51644. };
  51645. return SceneOptimizerOptions;
  51646. })();
  51647. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  51648. // Scene optimizer tool
  51649. var SceneOptimizer = (function () {
  51650. function SceneOptimizer() {
  51651. }
  51652. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  51653. // TODO: add an epsilon
  51654. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  51655. if (onSuccess) {
  51656. onSuccess();
  51657. }
  51658. return;
  51659. }
  51660. // Apply current level of optimizations
  51661. var allDone = true;
  51662. var noOptimizationApplied = true;
  51663. for (var index = 0; index < options.optimizations.length; index++) {
  51664. var optimization = options.optimizations[index];
  51665. if (optimization.priority === currentPriorityLevel) {
  51666. noOptimizationApplied = false;
  51667. allDone = allDone && optimization.apply(scene);
  51668. }
  51669. }
  51670. // If no optimization was applied, this is a failure :(
  51671. if (noOptimizationApplied) {
  51672. if (onFailure) {
  51673. onFailure();
  51674. }
  51675. return;
  51676. }
  51677. // If all optimizations were done, move to next level
  51678. if (allDone) {
  51679. currentPriorityLevel++;
  51680. }
  51681. // Let's the system running for a specific amount of time before checking FPS
  51682. scene.executeWhenReady(function () {
  51683. setTimeout(function () {
  51684. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  51685. }, options.trackerDuration);
  51686. });
  51687. };
  51688. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  51689. if (!options) {
  51690. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  51691. }
  51692. // Let's the system running for a specific amount of time before checking FPS
  51693. scene.executeWhenReady(function () {
  51694. setTimeout(function () {
  51695. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  51696. }, options.trackerDuration);
  51697. });
  51698. };
  51699. return SceneOptimizer;
  51700. })();
  51701. BABYLON.SceneOptimizer = SceneOptimizer;
  51702. })(BABYLON || (BABYLON = {}));
  51703. var BABYLON;
  51704. (function (BABYLON) {
  51705. var Internals;
  51706. (function (Internals) {
  51707. var MeshLODLevel = (function () {
  51708. function MeshLODLevel(distance, mesh) {
  51709. this.distance = distance;
  51710. this.mesh = mesh;
  51711. }
  51712. return MeshLODLevel;
  51713. })();
  51714. Internals.MeshLODLevel = MeshLODLevel;
  51715. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51716. })(BABYLON || (BABYLON = {}));
  51717. var BABYLON;
  51718. (function (BABYLON) {
  51719. var RawTexture = (function (_super) {
  51720. __extends(RawTexture, _super);
  51721. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51722. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51723. if (invertY === void 0) { invertY = false; }
  51724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51725. _super.call(this, null, scene, !generateMipMaps, invertY);
  51726. this.format = format;
  51727. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51728. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51729. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51730. }
  51731. RawTexture.prototype.update = function (data) {
  51732. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  51733. };
  51734. // Statics
  51735. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51736. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51737. if (invertY === void 0) { invertY = false; }
  51738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51739. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51740. };
  51741. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51742. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51743. if (invertY === void 0) { invertY = false; }
  51744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51745. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51746. };
  51747. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51748. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51749. if (invertY === void 0) { invertY = false; }
  51750. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51751. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51752. };
  51753. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51754. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51755. if (invertY === void 0) { invertY = false; }
  51756. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51757. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51758. };
  51759. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51760. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51761. if (invertY === void 0) { invertY = false; }
  51762. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51763. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51764. };
  51765. return RawTexture;
  51766. })(BABYLON.Texture);
  51767. BABYLON.RawTexture = RawTexture;
  51768. })(BABYLON || (BABYLON = {}));
  51769. var BABYLON;
  51770. (function (BABYLON) {
  51771. var IndexedVector2 = (function (_super) {
  51772. __extends(IndexedVector2, _super);
  51773. function IndexedVector2(original, index) {
  51774. _super.call(this, original.x, original.y);
  51775. this.index = index;
  51776. }
  51777. return IndexedVector2;
  51778. })(BABYLON.Vector2);
  51779. var PolygonPoints = (function () {
  51780. function PolygonPoints() {
  51781. this.elements = new Array();
  51782. }
  51783. PolygonPoints.prototype.add = function (originalPoints) {
  51784. var _this = this;
  51785. var result = new Array();
  51786. originalPoints.forEach(function (point) {
  51787. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  51788. var newPoint = new IndexedVector2(point, _this.elements.length);
  51789. result.push(newPoint);
  51790. _this.elements.push(newPoint);
  51791. }
  51792. });
  51793. return result;
  51794. };
  51795. PolygonPoints.prototype.computeBounds = function () {
  51796. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51797. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  51798. this.elements.forEach(function (point) {
  51799. // x
  51800. if (point.x < lmin.x) {
  51801. lmin.x = point.x;
  51802. }
  51803. else if (point.x > lmax.x) {
  51804. lmax.x = point.x;
  51805. }
  51806. // y
  51807. if (point.y < lmin.y) {
  51808. lmin.y = point.y;
  51809. }
  51810. else if (point.y > lmax.y) {
  51811. lmax.y = point.y;
  51812. }
  51813. });
  51814. return {
  51815. min: lmin,
  51816. max: lmax,
  51817. width: lmax.x - lmin.x,
  51818. height: lmax.y - lmin.y
  51819. };
  51820. };
  51821. return PolygonPoints;
  51822. })();
  51823. var Polygon = (function () {
  51824. function Polygon() {
  51825. }
  51826. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  51827. return [
  51828. new BABYLON.Vector2(xmin, ymin),
  51829. new BABYLON.Vector2(xmax, ymin),
  51830. new BABYLON.Vector2(xmax, ymax),
  51831. new BABYLON.Vector2(xmin, ymax)
  51832. ];
  51833. };
  51834. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  51835. if (cx === void 0) { cx = 0; }
  51836. if (cy === void 0) { cy = 0; }
  51837. if (numberOfSides === void 0) { numberOfSides = 32; }
  51838. var result = new Array();
  51839. var angle = 0;
  51840. var increment = (Math.PI * 2) / numberOfSides;
  51841. for (var i = 0; i < numberOfSides; i++) {
  51842. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  51843. angle -= increment;
  51844. }
  51845. return result;
  51846. };
  51847. Polygon.Parse = function (input) {
  51848. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  51849. var i, result = [];
  51850. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  51851. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  51852. }
  51853. return result;
  51854. };
  51855. Polygon.StartingAt = function (x, y) {
  51856. return BABYLON.Path2.StartingAt(x, y);
  51857. };
  51858. return Polygon;
  51859. })();
  51860. BABYLON.Polygon = Polygon;
  51861. var PolygonMeshBuilder = (function () {
  51862. function PolygonMeshBuilder(name, contours, scene) {
  51863. this._points = new PolygonPoints();
  51864. this._outlinepoints = new PolygonPoints();
  51865. this._holes = [];
  51866. this._epoints = new Array();
  51867. this._eholes = new Array();
  51868. this._name = name;
  51869. this._scene = scene;
  51870. var points;
  51871. if (contours instanceof BABYLON.Path2) {
  51872. points = contours.getPoints();
  51873. }
  51874. else {
  51875. points = contours;
  51876. }
  51877. this._addToepoint(points);
  51878. this._points.add(points);
  51879. this._outlinepoints.add(points);
  51880. }
  51881. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  51882. for (var _i = 0; _i < points.length; _i++) {
  51883. var p = points[_i];
  51884. this._epoints.push(p.x, p.y);
  51885. }
  51886. };
  51887. PolygonMeshBuilder.prototype.addHole = function (hole) {
  51888. this._points.add(hole);
  51889. var holepoints = new PolygonPoints();
  51890. holepoints.add(hole);
  51891. this._holes.push(holepoints);
  51892. this._eholes.push(this._epoints.length / 2);
  51893. this._addToepoint(hole);
  51894. return this;
  51895. };
  51896. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  51897. var _this = this;
  51898. if (updatable === void 0) { updatable = false; }
  51899. var result = new BABYLON.Mesh(this._name, this._scene);
  51900. var normals = [];
  51901. var positions = [];
  51902. var uvs = [];
  51903. var bounds = this._points.computeBounds();
  51904. this._points.elements.forEach(function (p) {
  51905. normals.push(0, 1.0, 0);
  51906. positions.push(p.x, 0, p.y);
  51907. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  51908. });
  51909. var indices = [];
  51910. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  51911. for (var i = 0; i < res.length; i++) {
  51912. indices.push(res[i]);
  51913. }
  51914. if (depth > 0) {
  51915. var positionscount = (positions.length / 3); //get the current pointcount
  51916. this._points.elements.forEach(function (p) {
  51917. normals.push(0, -1.0, 0);
  51918. positions.push(p.x, -depth, p.y);
  51919. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  51920. });
  51921. var totalCount = indices.length;
  51922. for (var i = 0; i < totalCount; i += 3) {
  51923. var i0 = indices[i + 0];
  51924. var i1 = indices[i + 1];
  51925. var i2 = indices[i + 2];
  51926. indices.push(i2 + positionscount);
  51927. indices.push(i1 + positionscount);
  51928. indices.push(i0 + positionscount);
  51929. }
  51930. //Add the sides
  51931. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  51932. this._holes.forEach(function (hole) {
  51933. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  51934. });
  51935. }
  51936. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  51937. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  51938. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  51939. result.setIndices(indices);
  51940. return result;
  51941. };
  51942. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  51943. var StartIndex = positions.length / 3;
  51944. var ulength = 0;
  51945. for (var i = 0; i < points.elements.length; i++) {
  51946. var p = points.elements[i];
  51947. var p1;
  51948. if ((i + 1) > points.elements.length - 1) {
  51949. p1 = points.elements[0];
  51950. }
  51951. else {
  51952. p1 = points.elements[i + 1];
  51953. }
  51954. positions.push(p.x, 0, p.y);
  51955. positions.push(p.x, -depth, p.y);
  51956. positions.push(p1.x, 0, p1.y);
  51957. positions.push(p1.x, -depth, p1.y);
  51958. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  51959. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  51960. var v3 = v2.subtract(v1);
  51961. var v4 = new BABYLON.Vector3(0, 1, 0);
  51962. var vn = BABYLON.Vector3.Cross(v3, v4);
  51963. vn = vn.normalize();
  51964. uvs.push(ulength / bounds.width, 0);
  51965. uvs.push(ulength / bounds.width, 1);
  51966. ulength += v3.length();
  51967. uvs.push((ulength / bounds.width), 0);
  51968. uvs.push((ulength / bounds.width), 1);
  51969. if (!flip) {
  51970. normals.push(-vn.x, -vn.y, -vn.z);
  51971. normals.push(-vn.x, -vn.y, -vn.z);
  51972. normals.push(-vn.x, -vn.y, -vn.z);
  51973. normals.push(-vn.x, -vn.y, -vn.z);
  51974. indices.push(StartIndex);
  51975. indices.push(StartIndex + 1);
  51976. indices.push(StartIndex + 2);
  51977. indices.push(StartIndex + 1);
  51978. indices.push(StartIndex + 3);
  51979. indices.push(StartIndex + 2);
  51980. }
  51981. else {
  51982. normals.push(vn.x, vn.y, vn.z);
  51983. normals.push(vn.x, vn.y, vn.z);
  51984. normals.push(vn.x, vn.y, vn.z);
  51985. normals.push(vn.x, vn.y, vn.z);
  51986. indices.push(StartIndex);
  51987. indices.push(StartIndex + 2);
  51988. indices.push(StartIndex + 1);
  51989. indices.push(StartIndex + 1);
  51990. indices.push(StartIndex + 2);
  51991. indices.push(StartIndex + 3);
  51992. }
  51993. StartIndex += 4;
  51994. }
  51995. ;
  51996. };
  51997. return PolygonMeshBuilder;
  51998. })();
  51999. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  52000. })(BABYLON || (BABYLON = {}));
  52001. var BABYLON;
  52002. (function (BABYLON) {
  52003. var Octree = (function () {
  52004. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  52005. if (maxDepth === void 0) { maxDepth = 2; }
  52006. this.maxDepth = maxDepth;
  52007. this.dynamicContent = new Array();
  52008. this._maxBlockCapacity = maxBlockCapacity || 64;
  52009. this._selectionContent = new BABYLON.SmartArray(1024);
  52010. this._creationFunc = creationFunc;
  52011. }
  52012. // Methods
  52013. Octree.prototype.update = function (worldMin, worldMax, entries) {
  52014. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  52015. };
  52016. Octree.prototype.addMesh = function (entry) {
  52017. for (var index = 0; index < this.blocks.length; index++) {
  52018. var block = this.blocks[index];
  52019. block.addEntry(entry);
  52020. }
  52021. };
  52022. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  52023. this._selectionContent.reset();
  52024. for (var index = 0; index < this.blocks.length; index++) {
  52025. var block = this.blocks[index];
  52026. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  52027. }
  52028. if (allowDuplicate) {
  52029. this._selectionContent.concat(this.dynamicContent);
  52030. }
  52031. else {
  52032. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  52033. }
  52034. return this._selectionContent;
  52035. };
  52036. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  52037. this._selectionContent.reset();
  52038. for (var index = 0; index < this.blocks.length; index++) {
  52039. var block = this.blocks[index];
  52040. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  52041. }
  52042. if (allowDuplicate) {
  52043. this._selectionContent.concat(this.dynamicContent);
  52044. }
  52045. else {
  52046. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  52047. }
  52048. return this._selectionContent;
  52049. };
  52050. Octree.prototype.intersectsRay = function (ray) {
  52051. this._selectionContent.reset();
  52052. for (var index = 0; index < this.blocks.length; index++) {
  52053. var block = this.blocks[index];
  52054. block.intersectsRay(ray, this._selectionContent);
  52055. }
  52056. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  52057. return this._selectionContent;
  52058. };
  52059. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  52060. target.blocks = new Array();
  52061. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  52062. // Segmenting space
  52063. for (var x = 0; x < 2; x++) {
  52064. for (var y = 0; y < 2; y++) {
  52065. for (var z = 0; z < 2; z++) {
  52066. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  52067. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  52068. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  52069. block.addEntries(entries);
  52070. target.blocks.push(block);
  52071. }
  52072. }
  52073. }
  52074. };
  52075. Octree.CreationFuncForMeshes = function (entry, block) {
  52076. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  52077. block.entries.push(entry);
  52078. }
  52079. };
  52080. Octree.CreationFuncForSubMeshes = function (entry, block) {
  52081. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  52082. block.entries.push(entry);
  52083. }
  52084. };
  52085. return Octree;
  52086. })();
  52087. BABYLON.Octree = Octree;
  52088. })(BABYLON || (BABYLON = {}));
  52089. var BABYLON;
  52090. (function (BABYLON) {
  52091. var OctreeBlock = (function () {
  52092. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  52093. this.entries = new Array();
  52094. this._boundingVectors = new Array();
  52095. this._capacity = capacity;
  52096. this._depth = depth;
  52097. this._maxDepth = maxDepth;
  52098. this._creationFunc = creationFunc;
  52099. this._minPoint = minPoint;
  52100. this._maxPoint = maxPoint;
  52101. this._boundingVectors.push(minPoint.clone());
  52102. this._boundingVectors.push(maxPoint.clone());
  52103. this._boundingVectors.push(minPoint.clone());
  52104. this._boundingVectors[2].x = maxPoint.x;
  52105. this._boundingVectors.push(minPoint.clone());
  52106. this._boundingVectors[3].y = maxPoint.y;
  52107. this._boundingVectors.push(minPoint.clone());
  52108. this._boundingVectors[4].z = maxPoint.z;
  52109. this._boundingVectors.push(maxPoint.clone());
  52110. this._boundingVectors[5].z = minPoint.z;
  52111. this._boundingVectors.push(maxPoint.clone());
  52112. this._boundingVectors[6].x = minPoint.x;
  52113. this._boundingVectors.push(maxPoint.clone());
  52114. this._boundingVectors[7].y = minPoint.y;
  52115. }
  52116. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  52117. // Property
  52118. get: function () {
  52119. return this._capacity;
  52120. },
  52121. enumerable: true,
  52122. configurable: true
  52123. });
  52124. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  52125. get: function () {
  52126. return this._minPoint;
  52127. },
  52128. enumerable: true,
  52129. configurable: true
  52130. });
  52131. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  52132. get: function () {
  52133. return this._maxPoint;
  52134. },
  52135. enumerable: true,
  52136. configurable: true
  52137. });
  52138. // Methods
  52139. OctreeBlock.prototype.addEntry = function (entry) {
  52140. if (this.blocks) {
  52141. for (var index = 0; index < this.blocks.length; index++) {
  52142. var block = this.blocks[index];
  52143. block.addEntry(entry);
  52144. }
  52145. return;
  52146. }
  52147. this._creationFunc(entry, this);
  52148. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  52149. this.createInnerBlocks();
  52150. }
  52151. };
  52152. OctreeBlock.prototype.addEntries = function (entries) {
  52153. for (var index = 0; index < entries.length; index++) {
  52154. var mesh = entries[index];
  52155. this.addEntry(mesh);
  52156. }
  52157. };
  52158. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  52159. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  52160. if (this.blocks) {
  52161. for (var index = 0; index < this.blocks.length; index++) {
  52162. var block = this.blocks[index];
  52163. block.select(frustumPlanes, selection, allowDuplicate);
  52164. }
  52165. return;
  52166. }
  52167. if (allowDuplicate) {
  52168. selection.concat(this.entries);
  52169. }
  52170. else {
  52171. selection.concatWithNoDuplicate(this.entries);
  52172. }
  52173. }
  52174. };
  52175. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  52176. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  52177. if (this.blocks) {
  52178. for (var index = 0; index < this.blocks.length; index++) {
  52179. var block = this.blocks[index];
  52180. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  52181. }
  52182. return;
  52183. }
  52184. if (allowDuplicate) {
  52185. selection.concat(this.entries);
  52186. }
  52187. else {
  52188. selection.concatWithNoDuplicate(this.entries);
  52189. }
  52190. }
  52191. };
  52192. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  52193. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  52194. if (this.blocks) {
  52195. for (var index = 0; index < this.blocks.length; index++) {
  52196. var block = this.blocks[index];
  52197. block.intersectsRay(ray, selection);
  52198. }
  52199. return;
  52200. }
  52201. selection.concatWithNoDuplicate(this.entries);
  52202. }
  52203. };
  52204. OctreeBlock.prototype.createInnerBlocks = function () {
  52205. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  52206. };
  52207. return OctreeBlock;
  52208. })();
  52209. BABYLON.OctreeBlock = OctreeBlock;
  52210. })(BABYLON || (BABYLON = {}));
  52211. var BABYLON;
  52212. (function (BABYLON) {
  52213. var BlurPostProcess = (function (_super) {
  52214. __extends(BlurPostProcess, _super);
  52215. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  52216. var _this = this;
  52217. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52218. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  52219. this.direction = direction;
  52220. this.blurWidth = blurWidth;
  52221. this.onApplyObservable.add(function (effect) {
  52222. effect.setFloat2("screenSize", _this.width, _this.height);
  52223. effect.setVector2("direction", _this.direction);
  52224. effect.setFloat("blurWidth", _this.blurWidth);
  52225. });
  52226. }
  52227. return BlurPostProcess;
  52228. })(BABYLON.PostProcess);
  52229. BABYLON.BlurPostProcess = BlurPostProcess;
  52230. })(BABYLON || (BABYLON = {}));
  52231. var BABYLON;
  52232. (function (BABYLON) {
  52233. var RefractionPostProcess = (function (_super) {
  52234. __extends(RefractionPostProcess, _super);
  52235. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  52236. var _this = this;
  52237. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  52238. this.color = color;
  52239. this.depth = depth;
  52240. this.colorLevel = colorLevel;
  52241. this.onActivateObservable.add(function (cam) {
  52242. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  52243. });
  52244. this.onApplyObservable.add(function (effect) {
  52245. effect.setColor3("baseColor", _this.color);
  52246. effect.setFloat("depth", _this.depth);
  52247. effect.setFloat("colorLevel", _this.colorLevel);
  52248. effect.setTexture("refractionSampler", _this._refRexture);
  52249. });
  52250. }
  52251. // Methods
  52252. RefractionPostProcess.prototype.dispose = function (camera) {
  52253. if (this._refRexture) {
  52254. this._refRexture.dispose();
  52255. }
  52256. _super.prototype.dispose.call(this, camera);
  52257. };
  52258. return RefractionPostProcess;
  52259. })(BABYLON.PostProcess);
  52260. BABYLON.RefractionPostProcess = RefractionPostProcess;
  52261. })(BABYLON || (BABYLON = {}));
  52262. var BABYLON;
  52263. (function (BABYLON) {
  52264. var BlackAndWhitePostProcess = (function (_super) {
  52265. __extends(BlackAndWhitePostProcess, _super);
  52266. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  52267. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  52268. }
  52269. return BlackAndWhitePostProcess;
  52270. })(BABYLON.PostProcess);
  52271. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  52272. })(BABYLON || (BABYLON = {}));
  52273. var BABYLON;
  52274. (function (BABYLON) {
  52275. var ConvolutionPostProcess = (function (_super) {
  52276. __extends(ConvolutionPostProcess, _super);
  52277. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  52278. var _this = this;
  52279. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  52280. this.kernel = kernel;
  52281. this.onApply = function (effect) {
  52282. effect.setFloat2("screenSize", _this.width, _this.height);
  52283. effect.setArray("kernel", _this.kernel);
  52284. };
  52285. }
  52286. // Statics
  52287. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  52288. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  52289. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  52290. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  52291. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  52292. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  52293. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  52294. return ConvolutionPostProcess;
  52295. })(BABYLON.PostProcess);
  52296. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  52297. })(BABYLON || (BABYLON = {}));
  52298. var BABYLON;
  52299. (function (BABYLON) {
  52300. var FilterPostProcess = (function (_super) {
  52301. __extends(FilterPostProcess, _super);
  52302. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  52303. var _this = this;
  52304. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  52305. this.kernelMatrix = kernelMatrix;
  52306. this.onApply = function (effect) {
  52307. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  52308. };
  52309. }
  52310. return FilterPostProcess;
  52311. })(BABYLON.PostProcess);
  52312. BABYLON.FilterPostProcess = FilterPostProcess;
  52313. })(BABYLON || (BABYLON = {}));
  52314. var BABYLON;
  52315. (function (BABYLON) {
  52316. var FxaaPostProcess = (function (_super) {
  52317. __extends(FxaaPostProcess, _super);
  52318. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  52319. var _this = this;
  52320. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  52321. this.onSizeChangedObservable.add(function () {
  52322. _this.texelWidth = 1.0 / _this.width;
  52323. _this.texelHeight = 1.0 / _this.height;
  52324. });
  52325. this.onApplyObservable.add(function (effect) {
  52326. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  52327. });
  52328. }
  52329. return FxaaPostProcess;
  52330. })(BABYLON.PostProcess);
  52331. BABYLON.FxaaPostProcess = FxaaPostProcess;
  52332. })(BABYLON || (BABYLON = {}));
  52333. var BABYLON;
  52334. (function (BABYLON) {
  52335. var StereoscopicInterlacePostProcess = (function (_super) {
  52336. __extends(StereoscopicInterlacePostProcess, _super);
  52337. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  52338. var _this = this;
  52339. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  52340. this._passedProcess = rigCameras[0]._rigPostProcess;
  52341. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  52342. this.onSizeChangedObservable.add(function () {
  52343. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  52344. });
  52345. this.onApplyObservable.add(function (effect) {
  52346. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  52347. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  52348. });
  52349. }
  52350. return StereoscopicInterlacePostProcess;
  52351. })(BABYLON.PostProcess);
  52352. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  52353. })(BABYLON || (BABYLON = {}));
  52354. var BABYLON;
  52355. (function (BABYLON) {
  52356. var LensFlare = (function () {
  52357. function LensFlare(size, position, color, imgUrl, system) {
  52358. this.size = size;
  52359. this.position = position;
  52360. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  52361. this.dispose = function () {
  52362. if (this.texture) {
  52363. this.texture.dispose();
  52364. }
  52365. // Remove from scene
  52366. var index = this._system.lensFlares.indexOf(this);
  52367. this._system.lensFlares.splice(index, 1);
  52368. };
  52369. this.color = color || new BABYLON.Color3(1, 1, 1);
  52370. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  52371. this._system = system;
  52372. system.lensFlares.push(this);
  52373. }
  52374. return LensFlare;
  52375. })();
  52376. BABYLON.LensFlare = LensFlare;
  52377. })(BABYLON || (BABYLON = {}));
  52378. var BABYLON;
  52379. (function (BABYLON) {
  52380. var LensFlareSystem = (function () {
  52381. function LensFlareSystem(name, emitter, scene) {
  52382. this.name = name;
  52383. this.lensFlares = new Array();
  52384. this.borderLimit = 300;
  52385. this.layerMask = 0x0FFFFFFF;
  52386. this._vertexBuffers = {};
  52387. this._isEnabled = true;
  52388. this._scene = scene;
  52389. this._emitter = emitter;
  52390. this.id = name;
  52391. scene.lensFlareSystems.push(this);
  52392. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  52393. var engine = scene.getEngine();
  52394. // VBO
  52395. var vertices = [];
  52396. vertices.push(1, 1);
  52397. vertices.push(-1, 1);
  52398. vertices.push(-1, -1);
  52399. vertices.push(1, -1);
  52400. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52401. // Indices
  52402. var indices = [];
  52403. indices.push(0);
  52404. indices.push(1);
  52405. indices.push(2);
  52406. indices.push(0);
  52407. indices.push(2);
  52408. indices.push(3);
  52409. this._indexBuffer = engine.createIndexBuffer(indices);
  52410. // Effects
  52411. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  52412. }
  52413. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  52414. get: function () {
  52415. return this._isEnabled;
  52416. },
  52417. set: function (value) {
  52418. this._isEnabled = value;
  52419. },
  52420. enumerable: true,
  52421. configurable: true
  52422. });
  52423. LensFlareSystem.prototype.getScene = function () {
  52424. return this._scene;
  52425. };
  52426. LensFlareSystem.prototype.getEmitter = function () {
  52427. return this._emitter;
  52428. };
  52429. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  52430. this._emitter = newEmitter;
  52431. };
  52432. LensFlareSystem.prototype.getEmitterPosition = function () {
  52433. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  52434. };
  52435. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  52436. var position = this.getEmitterPosition();
  52437. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  52438. this._positionX = position.x;
  52439. this._positionY = position.y;
  52440. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  52441. if (position.z > 0) {
  52442. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  52443. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  52444. return true;
  52445. }
  52446. }
  52447. return false;
  52448. };
  52449. LensFlareSystem.prototype._isVisible = function () {
  52450. if (!this._isEnabled) {
  52451. return false;
  52452. }
  52453. var emitterPosition = this.getEmitterPosition();
  52454. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  52455. var distance = direction.length();
  52456. direction.normalize();
  52457. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  52458. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  52459. return !pickInfo.hit || pickInfo.distance > distance;
  52460. };
  52461. LensFlareSystem.prototype.render = function () {
  52462. if (!this._effect.isReady())
  52463. return false;
  52464. var engine = this._scene.getEngine();
  52465. var viewport = this._scene.activeCamera.viewport;
  52466. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  52467. // Position
  52468. if (!this.computeEffectivePosition(globalViewport)) {
  52469. return false;
  52470. }
  52471. // Visibility
  52472. if (!this._isVisible()) {
  52473. return false;
  52474. }
  52475. // Intensity
  52476. var awayX;
  52477. var awayY;
  52478. if (this._positionX < this.borderLimit + globalViewport.x) {
  52479. awayX = this.borderLimit + globalViewport.x - this._positionX;
  52480. }
  52481. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  52482. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  52483. }
  52484. else {
  52485. awayX = 0;
  52486. }
  52487. if (this._positionY < this.borderLimit + globalViewport.y) {
  52488. awayY = this.borderLimit + globalViewport.y - this._positionY;
  52489. }
  52490. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  52491. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  52492. }
  52493. else {
  52494. awayY = 0;
  52495. }
  52496. var away = (awayX > awayY) ? awayX : awayY;
  52497. if (away > this.borderLimit) {
  52498. away = this.borderLimit;
  52499. }
  52500. var intensity = 1.0 - (away / this.borderLimit);
  52501. if (intensity < 0) {
  52502. return false;
  52503. }
  52504. if (intensity > 1.0) {
  52505. intensity = 1.0;
  52506. }
  52507. // Position
  52508. var centerX = globalViewport.x + globalViewport.width / 2;
  52509. var centerY = globalViewport.y + globalViewport.height / 2;
  52510. var distX = centerX - this._positionX;
  52511. var distY = centerY - this._positionY;
  52512. // Effects
  52513. engine.enableEffect(this._effect);
  52514. engine.setState(false);
  52515. engine.setDepthBuffer(false);
  52516. // VBOs
  52517. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52518. // Flares
  52519. for (var index = 0; index < this.lensFlares.length; index++) {
  52520. var flare = this.lensFlares[index];
  52521. engine.setAlphaMode(flare.alphaMode);
  52522. var x = centerX - (distX * flare.position);
  52523. var y = centerY - (distY * flare.position);
  52524. var cw = flare.size;
  52525. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  52526. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  52527. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  52528. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  52529. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  52530. // Texture
  52531. this._effect.setTexture("textureSampler", flare.texture);
  52532. // Color
  52533. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  52534. // Draw order
  52535. engine.draw(true, 0, 6);
  52536. }
  52537. engine.setDepthBuffer(true);
  52538. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52539. return true;
  52540. };
  52541. LensFlareSystem.prototype.dispose = function () {
  52542. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52543. if (vertexBuffer) {
  52544. vertexBuffer.dispose();
  52545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52546. }
  52547. if (this._indexBuffer) {
  52548. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52549. this._indexBuffer = null;
  52550. }
  52551. while (this.lensFlares.length) {
  52552. this.lensFlares[0].dispose();
  52553. }
  52554. // Remove from scene
  52555. var index = this._scene.lensFlareSystems.indexOf(this);
  52556. this._scene.lensFlareSystems.splice(index, 1);
  52557. };
  52558. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  52559. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  52560. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  52561. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  52562. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  52563. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  52564. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  52565. var parsedFlare = parsedLensFlareSystem.flares[index];
  52566. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  52567. }
  52568. return lensFlareSystem;
  52569. };
  52570. LensFlareSystem.prototype.serialize = function () {
  52571. var serializationObject = {};
  52572. serializationObject.id = this.id;
  52573. serializationObject.name = this.name;
  52574. serializationObject.emitterId = this.getEmitter().id;
  52575. serializationObject.borderLimit = this.borderLimit;
  52576. serializationObject.flares = [];
  52577. for (var index = 0; index < this.lensFlares.length; index++) {
  52578. var flare = this.lensFlares[index];
  52579. serializationObject.flares.push({
  52580. size: flare.size,
  52581. position: flare.position,
  52582. color: flare.color.asArray(),
  52583. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  52584. });
  52585. }
  52586. return serializationObject;
  52587. };
  52588. return LensFlareSystem;
  52589. })();
  52590. BABYLON.LensFlareSystem = LensFlareSystem;
  52591. })(BABYLON || (BABYLON = {}));
  52592. var BABYLON;
  52593. (function (BABYLON) {
  52594. // We're mainly based on the logic defined into the FreeCamera code
  52595. var DeviceOrientationCamera = (function (_super) {
  52596. __extends(DeviceOrientationCamera, _super);
  52597. //-- end properties for backward compatibility for inputs
  52598. function DeviceOrientationCamera(name, position, scene) {
  52599. _super.call(this, name, position, scene);
  52600. this.inputs.addDeviceOrientation();
  52601. }
  52602. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  52603. //-- Begin properties for backward compatibility for inputs
  52604. get: function () {
  52605. return 0;
  52606. },
  52607. set: function (value) {
  52608. },
  52609. enumerable: true,
  52610. configurable: true
  52611. });
  52612. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  52613. get: function () {
  52614. return 0;
  52615. },
  52616. set: function (value) {
  52617. },
  52618. enumerable: true,
  52619. configurable: true
  52620. });
  52621. DeviceOrientationCamera.prototype.getTypeName = function () {
  52622. return "DeviceOrientationCamera";
  52623. };
  52624. return DeviceOrientationCamera;
  52625. })(BABYLON.FreeCamera);
  52626. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  52627. })(BABYLON || (BABYLON = {}));
  52628. var BABYLON;
  52629. (function (BABYLON) {
  52630. // We're mainly based on the logic defined into the FreeCamera code
  52631. var UniversalCamera = (function (_super) {
  52632. __extends(UniversalCamera, _super);
  52633. //-- end properties for backward compatibility for inputs
  52634. function UniversalCamera(name, position, scene) {
  52635. _super.call(this, name, position, scene);
  52636. this.inputs.addGamepad();
  52637. }
  52638. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52639. //-- Begin properties for backward compatibility for inputs
  52640. get: function () {
  52641. var gamepad = this.inputs.attached["gamepad"];
  52642. if (gamepad)
  52643. return gamepad.gamepadAngularSensibility;
  52644. },
  52645. set: function (value) {
  52646. var gamepad = this.inputs.attached["gamepad"];
  52647. if (gamepad)
  52648. gamepad.gamepadAngularSensibility = value;
  52649. },
  52650. enumerable: true,
  52651. configurable: true
  52652. });
  52653. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52654. get: function () {
  52655. var gamepad = this.inputs.attached["gamepad"];
  52656. if (gamepad)
  52657. return gamepad.gamepadMoveSensibility;
  52658. },
  52659. set: function (value) {
  52660. var gamepad = this.inputs.attached["gamepad"];
  52661. if (gamepad)
  52662. gamepad.gamepadMoveSensibility = value;
  52663. },
  52664. enumerable: true,
  52665. configurable: true
  52666. });
  52667. UniversalCamera.prototype.getTypeName = function () {
  52668. return "UniversalCamera";
  52669. };
  52670. return UniversalCamera;
  52671. })(BABYLON.TouchCamera);
  52672. BABYLON.UniversalCamera = UniversalCamera;
  52673. })(BABYLON || (BABYLON = {}));
  52674. var BABYLON;
  52675. (function (BABYLON) {
  52676. var Gamepads = (function () {
  52677. function Gamepads(ongamedpadconnected) {
  52678. var _this = this;
  52679. this.babylonGamepads = [];
  52680. this.oneGamepadConnected = false;
  52681. this.isMonitoring = false;
  52682. this.gamepadEventSupported = 'GamepadEvent' in window;
  52683. this.gamepadSupportAvailable = (navigator.getGamepads ||
  52684. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  52685. this._callbackGamepadConnected = ongamedpadconnected;
  52686. if (this.gamepadSupportAvailable) {
  52687. // Checking if the gamepad connected event is supported (like in Firefox)
  52688. if (this.gamepadEventSupported) {
  52689. this._onGamepadConnectedEvent = function (evt) {
  52690. _this._onGamepadConnected(evt);
  52691. };
  52692. this._onGamepadDisonnectedEvent = function (evt) {
  52693. _this._onGamepadDisconnected(evt);
  52694. };
  52695. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52696. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52697. }
  52698. else {
  52699. this._startMonitoringGamepads();
  52700. }
  52701. }
  52702. }
  52703. Gamepads.prototype.dispose = function () {
  52704. if (Gamepads.gamepadDOMInfo) {
  52705. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52706. }
  52707. if (this._onGamepadConnectedEvent) {
  52708. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  52709. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  52710. this._onGamepadConnectedEvent = null;
  52711. this._onGamepadDisonnectedEvent = null;
  52712. }
  52713. };
  52714. Gamepads.prototype._onGamepadConnected = function (evt) {
  52715. var newGamepad = this._addNewGamepad(evt.gamepad);
  52716. if (this._callbackGamepadConnected)
  52717. this._callbackGamepadConnected(newGamepad);
  52718. this._startMonitoringGamepads();
  52719. };
  52720. Gamepads.prototype._addNewGamepad = function (gamepad) {
  52721. if (!this.oneGamepadConnected) {
  52722. this.oneGamepadConnected = true;
  52723. if (Gamepads.gamepadDOMInfo) {
  52724. document.body.removeChild(Gamepads.gamepadDOMInfo);
  52725. Gamepads.gamepadDOMInfo = null;
  52726. }
  52727. }
  52728. var newGamepad;
  52729. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  52730. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  52731. }
  52732. else {
  52733. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  52734. }
  52735. this.babylonGamepads.push(newGamepad);
  52736. return newGamepad;
  52737. };
  52738. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  52739. // Remove the gamepad from the list of gamepads to monitor.
  52740. for (var i in this.babylonGamepads) {
  52741. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  52742. this.babylonGamepads.splice(+i, 1);
  52743. break;
  52744. }
  52745. }
  52746. // If no gamepads are left, stop the polling loop.
  52747. if (this.babylonGamepads.length == 0) {
  52748. this._stopMonitoringGamepads();
  52749. }
  52750. };
  52751. Gamepads.prototype._startMonitoringGamepads = function () {
  52752. if (!this.isMonitoring) {
  52753. this.isMonitoring = true;
  52754. this._checkGamepadsStatus();
  52755. }
  52756. };
  52757. Gamepads.prototype._stopMonitoringGamepads = function () {
  52758. this.isMonitoring = false;
  52759. };
  52760. Gamepads.prototype._checkGamepadsStatus = function () {
  52761. var _this = this;
  52762. // updating gamepad objects
  52763. this._updateGamepadObjects();
  52764. for (var i in this.babylonGamepads) {
  52765. this.babylonGamepads[i].update();
  52766. }
  52767. if (this.isMonitoring) {
  52768. if (window.requestAnimationFrame) {
  52769. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52770. }
  52771. else if (window.mozRequestAnimationFrame) {
  52772. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52773. }
  52774. else if (window.webkitRequestAnimationFrame) {
  52775. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  52776. }
  52777. }
  52778. };
  52779. // This function is called only on Chrome, which does not yet support
  52780. // connection/disconnection events, but requires you to monitor
  52781. // an array for changes.
  52782. Gamepads.prototype._updateGamepadObjects = function () {
  52783. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  52784. for (var i = 0; i < gamepads.length; i++) {
  52785. if (gamepads[i]) {
  52786. if (!(gamepads[i].index in this.babylonGamepads)) {
  52787. var newGamepad = this._addNewGamepad(gamepads[i]);
  52788. if (this._callbackGamepadConnected) {
  52789. this._callbackGamepadConnected(newGamepad);
  52790. }
  52791. }
  52792. else {
  52793. this.babylonGamepads[i].browserGamepad = gamepads[i];
  52794. }
  52795. }
  52796. }
  52797. };
  52798. return Gamepads;
  52799. })();
  52800. BABYLON.Gamepads = Gamepads;
  52801. var StickValues = (function () {
  52802. function StickValues(x, y) {
  52803. this.x = x;
  52804. this.y = y;
  52805. }
  52806. return StickValues;
  52807. })();
  52808. BABYLON.StickValues = StickValues;
  52809. var Gamepad = (function () {
  52810. function Gamepad(id, index, browserGamepad) {
  52811. this.id = id;
  52812. this.index = index;
  52813. this.browserGamepad = browserGamepad;
  52814. if (this.browserGamepad.axes.length >= 2) {
  52815. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52816. }
  52817. if (this.browserGamepad.axes.length >= 4) {
  52818. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52819. }
  52820. }
  52821. Gamepad.prototype.onleftstickchanged = function (callback) {
  52822. this._onleftstickchanged = callback;
  52823. };
  52824. Gamepad.prototype.onrightstickchanged = function (callback) {
  52825. this._onrightstickchanged = callback;
  52826. };
  52827. Object.defineProperty(Gamepad.prototype, "leftStick", {
  52828. get: function () {
  52829. return this._leftStick;
  52830. },
  52831. set: function (newValues) {
  52832. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  52833. this._onleftstickchanged(newValues);
  52834. }
  52835. this._leftStick = newValues;
  52836. },
  52837. enumerable: true,
  52838. configurable: true
  52839. });
  52840. Object.defineProperty(Gamepad.prototype, "rightStick", {
  52841. get: function () {
  52842. return this._rightStick;
  52843. },
  52844. set: function (newValues) {
  52845. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  52846. this._onrightstickchanged(newValues);
  52847. }
  52848. this._rightStick = newValues;
  52849. },
  52850. enumerable: true,
  52851. configurable: true
  52852. });
  52853. Gamepad.prototype.update = function () {
  52854. if (this._leftStick) {
  52855. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  52856. }
  52857. if (this._rightStick) {
  52858. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  52859. }
  52860. };
  52861. return Gamepad;
  52862. })();
  52863. BABYLON.Gamepad = Gamepad;
  52864. var GenericPad = (function (_super) {
  52865. __extends(GenericPad, _super);
  52866. function GenericPad(id, index, gamepad) {
  52867. _super.call(this, id, index, gamepad);
  52868. this.id = id;
  52869. this.index = index;
  52870. this.gamepad = gamepad;
  52871. this._buttons = new Array(gamepad.buttons.length);
  52872. }
  52873. GenericPad.prototype.onbuttondown = function (callback) {
  52874. this._onbuttondown = callback;
  52875. };
  52876. GenericPad.prototype.onbuttonup = function (callback) {
  52877. this._onbuttonup = callback;
  52878. };
  52879. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  52880. if (newValue !== currentValue) {
  52881. if (this._onbuttondown && newValue === 1) {
  52882. this._onbuttondown(buttonIndex);
  52883. }
  52884. if (this._onbuttonup && newValue === 0) {
  52885. this._onbuttonup(buttonIndex);
  52886. }
  52887. }
  52888. return newValue;
  52889. };
  52890. GenericPad.prototype.update = function () {
  52891. _super.prototype.update.call(this);
  52892. for (var index = 0; index < this._buttons.length; index++) {
  52893. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  52894. }
  52895. };
  52896. return GenericPad;
  52897. })(Gamepad);
  52898. BABYLON.GenericPad = GenericPad;
  52899. (function (Xbox360Button) {
  52900. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  52901. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  52902. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  52903. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  52904. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  52905. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  52906. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  52907. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  52908. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  52909. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  52910. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  52911. var Xbox360Button = BABYLON.Xbox360Button;
  52912. (function (Xbox360Dpad) {
  52913. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  52914. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  52915. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  52916. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  52917. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  52918. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  52919. var Xbox360Pad = (function (_super) {
  52920. __extends(Xbox360Pad, _super);
  52921. function Xbox360Pad() {
  52922. _super.apply(this, arguments);
  52923. this._leftTrigger = 0;
  52924. this._rightTrigger = 0;
  52925. this._buttonA = 0;
  52926. this._buttonB = 0;
  52927. this._buttonX = 0;
  52928. this._buttonY = 0;
  52929. this._buttonBack = 0;
  52930. this._buttonStart = 0;
  52931. this._buttonLB = 0;
  52932. this._buttonRB = 0;
  52933. this._buttonLeftStick = 0;
  52934. this._buttonRightStick = 0;
  52935. this._dPadUp = 0;
  52936. this._dPadDown = 0;
  52937. this._dPadLeft = 0;
  52938. this._dPadRight = 0;
  52939. }
  52940. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  52941. this._onlefttriggerchanged = callback;
  52942. };
  52943. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  52944. this._onrighttriggerchanged = callback;
  52945. };
  52946. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  52947. get: function () {
  52948. return this._leftTrigger;
  52949. },
  52950. set: function (newValue) {
  52951. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  52952. this._onlefttriggerchanged(newValue);
  52953. }
  52954. this._leftTrigger = newValue;
  52955. },
  52956. enumerable: true,
  52957. configurable: true
  52958. });
  52959. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  52960. get: function () {
  52961. return this._rightTrigger;
  52962. },
  52963. set: function (newValue) {
  52964. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  52965. this._onrighttriggerchanged(newValue);
  52966. }
  52967. this._rightTrigger = newValue;
  52968. },
  52969. enumerable: true,
  52970. configurable: true
  52971. });
  52972. Xbox360Pad.prototype.onbuttondown = function (callback) {
  52973. this._onbuttondown = callback;
  52974. };
  52975. Xbox360Pad.prototype.onbuttonup = function (callback) {
  52976. this._onbuttonup = callback;
  52977. };
  52978. Xbox360Pad.prototype.ondpaddown = function (callback) {
  52979. this._ondpaddown = callback;
  52980. };
  52981. Xbox360Pad.prototype.ondpadup = function (callback) {
  52982. this._ondpadup = callback;
  52983. };
  52984. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  52985. if (newValue !== currentValue) {
  52986. if (this._onbuttondown && newValue === 1) {
  52987. this._onbuttondown(buttonType);
  52988. }
  52989. if (this._onbuttonup && newValue === 0) {
  52990. this._onbuttonup(buttonType);
  52991. }
  52992. }
  52993. return newValue;
  52994. };
  52995. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  52996. if (newValue !== currentValue) {
  52997. if (this._ondpaddown && newValue === 1) {
  52998. this._ondpaddown(buttonType);
  52999. }
  53000. if (this._ondpadup && newValue === 0) {
  53001. this._ondpadup(buttonType);
  53002. }
  53003. }
  53004. return newValue;
  53005. };
  53006. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  53007. get: function () {
  53008. return this._buttonA;
  53009. },
  53010. set: function (value) {
  53011. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  53012. },
  53013. enumerable: true,
  53014. configurable: true
  53015. });
  53016. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  53017. get: function () {
  53018. return this._buttonB;
  53019. },
  53020. set: function (value) {
  53021. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  53022. },
  53023. enumerable: true,
  53024. configurable: true
  53025. });
  53026. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  53027. get: function () {
  53028. return this._buttonX;
  53029. },
  53030. set: function (value) {
  53031. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  53032. },
  53033. enumerable: true,
  53034. configurable: true
  53035. });
  53036. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  53037. get: function () {
  53038. return this._buttonY;
  53039. },
  53040. set: function (value) {
  53041. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  53042. },
  53043. enumerable: true,
  53044. configurable: true
  53045. });
  53046. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  53047. get: function () {
  53048. return this._buttonStart;
  53049. },
  53050. set: function (value) {
  53051. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  53052. },
  53053. enumerable: true,
  53054. configurable: true
  53055. });
  53056. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  53057. get: function () {
  53058. return this._buttonBack;
  53059. },
  53060. set: function (value) {
  53061. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  53062. },
  53063. enumerable: true,
  53064. configurable: true
  53065. });
  53066. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  53067. get: function () {
  53068. return this._buttonLB;
  53069. },
  53070. set: function (value) {
  53071. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  53072. },
  53073. enumerable: true,
  53074. configurable: true
  53075. });
  53076. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  53077. get: function () {
  53078. return this._buttonRB;
  53079. },
  53080. set: function (value) {
  53081. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  53082. },
  53083. enumerable: true,
  53084. configurable: true
  53085. });
  53086. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  53087. get: function () {
  53088. return this._buttonLeftStick;
  53089. },
  53090. set: function (value) {
  53091. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  53092. },
  53093. enumerable: true,
  53094. configurable: true
  53095. });
  53096. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  53097. get: function () {
  53098. return this._buttonRightStick;
  53099. },
  53100. set: function (value) {
  53101. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  53102. },
  53103. enumerable: true,
  53104. configurable: true
  53105. });
  53106. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  53107. get: function () {
  53108. return this._dPadUp;
  53109. },
  53110. set: function (value) {
  53111. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  53112. },
  53113. enumerable: true,
  53114. configurable: true
  53115. });
  53116. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  53117. get: function () {
  53118. return this._dPadDown;
  53119. },
  53120. set: function (value) {
  53121. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  53127. get: function () {
  53128. return this._dPadLeft;
  53129. },
  53130. set: function (value) {
  53131. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53132. },
  53133. enumerable: true,
  53134. configurable: true
  53135. });
  53136. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53137. get: function () {
  53138. return this._dPadRight;
  53139. },
  53140. set: function (value) {
  53141. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53142. },
  53143. enumerable: true,
  53144. configurable: true
  53145. });
  53146. Xbox360Pad.prototype.update = function () {
  53147. _super.prototype.update.call(this);
  53148. this.buttonA = this.browserGamepad.buttons[0].value;
  53149. this.buttonB = this.browserGamepad.buttons[1].value;
  53150. this.buttonX = this.browserGamepad.buttons[2].value;
  53151. this.buttonY = this.browserGamepad.buttons[3].value;
  53152. this.buttonLB = this.browserGamepad.buttons[4].value;
  53153. this.buttonRB = this.browserGamepad.buttons[5].value;
  53154. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53155. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53156. this.buttonBack = this.browserGamepad.buttons[8].value;
  53157. this.buttonStart = this.browserGamepad.buttons[9].value;
  53158. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53159. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53160. this.dPadUp = this.browserGamepad.buttons[12].value;
  53161. this.dPadDown = this.browserGamepad.buttons[13].value;
  53162. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53163. this.dPadRight = this.browserGamepad.buttons[15].value;
  53164. };
  53165. return Xbox360Pad;
  53166. })(Gamepad);
  53167. BABYLON.Xbox360Pad = Xbox360Pad;
  53168. })(BABYLON || (BABYLON = {}));
  53169. var BABYLON;
  53170. (function (BABYLON) {
  53171. // We're mainly based on the logic defined into the FreeCamera code
  53172. var GamepadCamera = (function (_super) {
  53173. __extends(GamepadCamera, _super);
  53174. //-- end properties for backward compatibility for inputs
  53175. function GamepadCamera(name, position, scene) {
  53176. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  53177. _super.call(this, name, position, scene);
  53178. }
  53179. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  53180. //-- Begin properties for backward compatibility for inputs
  53181. get: function () {
  53182. var gamepad = this.inputs.attached["gamepad"];
  53183. if (gamepad)
  53184. return gamepad.gamepadAngularSensibility;
  53185. },
  53186. set: function (value) {
  53187. var gamepad = this.inputs.attached["gamepad"];
  53188. if (gamepad)
  53189. gamepad.gamepadAngularSensibility = value;
  53190. },
  53191. enumerable: true,
  53192. configurable: true
  53193. });
  53194. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  53195. get: function () {
  53196. var gamepad = this.inputs.attached["gamepad"];
  53197. if (gamepad)
  53198. return gamepad.gamepadMoveSensibility;
  53199. },
  53200. set: function (value) {
  53201. var gamepad = this.inputs.attached["gamepad"];
  53202. if (gamepad)
  53203. gamepad.gamepadMoveSensibility = value;
  53204. },
  53205. enumerable: true,
  53206. configurable: true
  53207. });
  53208. GamepadCamera.prototype.getTypeName = function () {
  53209. return "GamepadCamera";
  53210. };
  53211. return GamepadCamera;
  53212. })(BABYLON.UniversalCamera);
  53213. BABYLON.GamepadCamera = GamepadCamera;
  53214. })(BABYLON || (BABYLON = {}));
  53215. var BABYLON;
  53216. (function (BABYLON) {
  53217. var Analyser = (function () {
  53218. function Analyser(scene) {
  53219. this.SMOOTHING = 0.75;
  53220. this.FFT_SIZE = 512;
  53221. this.BARGRAPHAMPLITUDE = 256;
  53222. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53223. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53224. this._scene = scene;
  53225. this._audioEngine = BABYLON.Engine.audioEngine;
  53226. if (this._audioEngine.canUseWebAudio) {
  53227. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53228. this._webAudioAnalyser.minDecibels = -140;
  53229. this._webAudioAnalyser.maxDecibels = 0;
  53230. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53231. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53232. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53233. }
  53234. }
  53235. Analyser.prototype.getFrequencyBinCount = function () {
  53236. if (this._audioEngine.canUseWebAudio) {
  53237. return this._webAudioAnalyser.frequencyBinCount;
  53238. }
  53239. else {
  53240. return 0;
  53241. }
  53242. };
  53243. Analyser.prototype.getByteFrequencyData = function () {
  53244. if (this._audioEngine.canUseWebAudio) {
  53245. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53246. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53247. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53248. }
  53249. return this._byteFreqs;
  53250. };
  53251. Analyser.prototype.getByteTimeDomainData = function () {
  53252. if (this._audioEngine.canUseWebAudio) {
  53253. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53254. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53255. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53256. }
  53257. return this._byteTime;
  53258. };
  53259. Analyser.prototype.getFloatFrequencyData = function () {
  53260. if (this._audioEngine.canUseWebAudio) {
  53261. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53262. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53263. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53264. }
  53265. return this._floatFreqs;
  53266. };
  53267. Analyser.prototype.drawDebugCanvas = function () {
  53268. var _this = this;
  53269. if (this._audioEngine.canUseWebAudio) {
  53270. if (!this._debugCanvas) {
  53271. this._debugCanvas = document.createElement("canvas");
  53272. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53273. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53274. this._debugCanvas.style.position = "absolute";
  53275. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53276. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53277. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53278. document.body.appendChild(this._debugCanvas);
  53279. this._registerFunc = function () {
  53280. _this.drawDebugCanvas();
  53281. };
  53282. this._scene.registerBeforeRender(this._registerFunc);
  53283. }
  53284. if (this._registerFunc) {
  53285. var workingArray = this.getByteFrequencyData();
  53286. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53287. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53288. // Draw the frequency domain chart.
  53289. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53290. var value = workingArray[i];
  53291. var percent = value / this.BARGRAPHAMPLITUDE;
  53292. var height = this.DEBUGCANVASSIZE.height * percent;
  53293. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53294. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53295. var hue = i / this.getFrequencyBinCount() * 360;
  53296. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53297. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53298. }
  53299. }
  53300. }
  53301. };
  53302. Analyser.prototype.stopDebugCanvas = function () {
  53303. if (this._debugCanvas) {
  53304. this._scene.unregisterBeforeRender(this._registerFunc);
  53305. this._registerFunc = null;
  53306. document.body.removeChild(this._debugCanvas);
  53307. this._debugCanvas = null;
  53308. this._debugCanvasContext = null;
  53309. }
  53310. };
  53311. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53312. if (this._audioEngine.canUseWebAudio) {
  53313. inputAudioNode.connect(this._webAudioAnalyser);
  53314. this._webAudioAnalyser.connect(outputAudioNode);
  53315. }
  53316. };
  53317. Analyser.prototype.dispose = function () {
  53318. if (this._audioEngine.canUseWebAudio) {
  53319. this._webAudioAnalyser.disconnect();
  53320. }
  53321. };
  53322. return Analyser;
  53323. })();
  53324. BABYLON.Analyser = Analyser;
  53325. })(BABYLON || (BABYLON = {}));
  53326. var BABYLON;
  53327. (function (BABYLON) {
  53328. var DepthRenderer = (function () {
  53329. function DepthRenderer(scene, type) {
  53330. var _this = this;
  53331. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  53332. this._viewMatrix = BABYLON.Matrix.Zero();
  53333. this._projectionMatrix = BABYLON.Matrix.Zero();
  53334. this._transformMatrix = BABYLON.Matrix.Zero();
  53335. this._worldViewProjection = BABYLON.Matrix.Zero();
  53336. this._scene = scene;
  53337. var engine = scene.getEngine();
  53338. // Render target
  53339. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  53340. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53341. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53342. this._depthMap.refreshRate = 1;
  53343. this._depthMap.renderParticles = false;
  53344. this._depthMap.renderList = null;
  53345. // set default depth value to 1.0 (far away)
  53346. this._depthMap.onClearObservable.add(function (engine) {
  53347. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  53348. });
  53349. // Custom render function
  53350. var renderSubMesh = function (subMesh) {
  53351. var mesh = subMesh.getRenderingMesh();
  53352. var scene = _this._scene;
  53353. var engine = scene.getEngine();
  53354. // Culling
  53355. engine.setState(subMesh.getMaterial().backFaceCulling);
  53356. // Managing instances
  53357. var batch = mesh._getInstancesRenderList(subMesh._id);
  53358. if (batch.mustReturn) {
  53359. return;
  53360. }
  53361. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53362. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53363. engine.enableEffect(_this._effect);
  53364. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  53365. var material = subMesh.getMaterial();
  53366. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  53367. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  53368. // Alpha test
  53369. if (material && material.needAlphaTesting()) {
  53370. var alphaTexture = material.getAlphaTestTexture();
  53371. _this._effect.setTexture("diffuseSampler", alphaTexture);
  53372. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53373. }
  53374. // Bones
  53375. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53376. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53377. }
  53378. // Draw
  53379. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53380. }
  53381. };
  53382. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  53383. var index;
  53384. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53385. renderSubMesh(opaqueSubMeshes.data[index]);
  53386. }
  53387. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53388. renderSubMesh(alphaTestSubMeshes.data[index]);
  53389. }
  53390. };
  53391. }
  53392. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  53393. var material = subMesh.getMaterial();
  53394. if (material.disableDepthWrite) {
  53395. return false;
  53396. }
  53397. var defines = [];
  53398. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53399. var mesh = subMesh.getMesh();
  53400. var scene = mesh.getScene();
  53401. // Alpha test
  53402. if (material && material.needAlphaTesting()) {
  53403. defines.push("#define ALPHATEST");
  53404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53405. attribs.push(BABYLON.VertexBuffer.UVKind);
  53406. defines.push("#define UV1");
  53407. }
  53408. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53410. defines.push("#define UV2");
  53411. }
  53412. }
  53413. // Bones
  53414. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53415. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53416. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53417. if (mesh.numBoneInfluencers > 4) {
  53418. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53419. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53420. }
  53421. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53422. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53423. }
  53424. else {
  53425. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53426. }
  53427. // Instances
  53428. if (useInstances) {
  53429. defines.push("#define INSTANCES");
  53430. attribs.push("world0");
  53431. attribs.push("world1");
  53432. attribs.push("world2");
  53433. attribs.push("world3");
  53434. }
  53435. // Get correct effect
  53436. var join = defines.join("\n");
  53437. if (this._cachedDefines !== join) {
  53438. this._cachedDefines = join;
  53439. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  53440. }
  53441. return this._effect.isReady();
  53442. };
  53443. DepthRenderer.prototype.getDepthMap = function () {
  53444. return this._depthMap;
  53445. };
  53446. // Methods
  53447. DepthRenderer.prototype.dispose = function () {
  53448. this._depthMap.dispose();
  53449. };
  53450. return DepthRenderer;
  53451. })();
  53452. BABYLON.DepthRenderer = DepthRenderer;
  53453. })(BABYLON || (BABYLON = {}));
  53454. var BABYLON;
  53455. (function (BABYLON) {
  53456. var SSAORenderingPipeline = (function (_super) {
  53457. __extends(SSAORenderingPipeline, _super);
  53458. /**
  53459. * @constructor
  53460. * @param {string} name - The rendering pipeline name
  53461. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53462. * @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 }
  53463. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53464. */
  53465. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  53466. var _this = this;
  53467. _super.call(this, scene.getEngine(), name);
  53468. // Members
  53469. /**
  53470. * The PassPostProcess id in the pipeline that contains the original scene color
  53471. * @type {string}
  53472. */
  53473. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53474. /**
  53475. * The SSAO PostProcess id in the pipeline
  53476. * @type {string}
  53477. */
  53478. this.SSAORenderEffect = "SSAORenderEffect";
  53479. /**
  53480. * The horizontal blur PostProcess id in the pipeline
  53481. * @type {string}
  53482. */
  53483. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53484. /**
  53485. * The vertical blur PostProcess id in the pipeline
  53486. * @type {string}
  53487. */
  53488. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53489. /**
  53490. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53491. * @type {string}
  53492. */
  53493. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53494. /**
  53495. * The output strength of the SSAO post-process. Default value is 1.0.
  53496. * @type {number}
  53497. */
  53498. this.totalStrength = 1.0;
  53499. /**
  53500. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  53501. * @type {number}
  53502. */
  53503. this.radius = 0.0001;
  53504. /**
  53505. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  53506. * Must not be equal to fallOff and superior to fallOff.
  53507. * Default value is 0.975
  53508. * @type {number}
  53509. */
  53510. this.area = 0.0075;
  53511. /**
  53512. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  53513. * Must not be equal to area and inferior to area.
  53514. * Default value is 0.0
  53515. * @type {number}
  53516. */
  53517. this.fallOff = 0.000001;
  53518. /**
  53519. * The base color of the SSAO post-process
  53520. * The final result is "base + ssao" between [0, 1]
  53521. * @type {number}
  53522. */
  53523. this.base = 0.5;
  53524. this._firstUpdate = true;
  53525. this._scene = scene;
  53526. // Set up assets
  53527. this._createRandomTexture();
  53528. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53529. var ssaoRatio = ratio.ssaoRatio || ratio;
  53530. var combineRatio = ratio.combineRatio || ratio;
  53531. this._ratio = {
  53532. ssaoRatio: ssaoRatio,
  53533. combineRatio: combineRatio
  53534. };
  53535. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53536. this._createSSAOPostProcess(ssaoRatio);
  53537. this._createBlurPostProcess(ssaoRatio);
  53538. this._createSSAOCombinePostProcess(combineRatio);
  53539. // Set up pipeline
  53540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53543. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53544. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53545. // Finish
  53546. scene.postProcessRenderPipelineManager.addPipeline(this);
  53547. if (cameras)
  53548. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53549. }
  53550. // Public Methods
  53551. /**
  53552. * Returns the horizontal blur PostProcess
  53553. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  53554. */
  53555. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  53556. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  53557. return null;
  53558. };
  53559. /**
  53560. * Returns the vertical blur PostProcess
  53561. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  53562. */
  53563. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  53564. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  53565. return null;
  53566. };
  53567. /**
  53568. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53569. */
  53570. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53571. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53572. for (var i = 0; i < this._scene.cameras.length; i++) {
  53573. var camera = this._scene.cameras[i];
  53574. this._originalColorPostProcess.dispose(camera);
  53575. this._ssaoPostProcess.dispose(camera);
  53576. this._blurHPostProcess.dispose(camera);
  53577. this._blurVPostProcess.dispose(camera);
  53578. this._ssaoCombinePostProcess.dispose(camera);
  53579. }
  53580. this._randomTexture.dispose();
  53581. if (disableDepthRender)
  53582. this._scene.disableDepthRenderer();
  53583. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53584. };
  53585. // Private Methods
  53586. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53587. var _this = this;
  53588. /*
  53589. var samplerOffsets = [
  53590. -8.0, -6.0, -4.0, -2.0,
  53591. 0.0,
  53592. 2.0, 4.0, 6.0, 8.0
  53593. ];
  53594. */
  53595. var samples = 16;
  53596. var samplerOffsets = [];
  53597. for (var i = -8; i < 8; i++) {
  53598. samplerOffsets.push(i * 2);
  53599. }
  53600. 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");
  53601. this._blurHPostProcess.onApply = function (effect) {
  53602. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53603. effect.setTexture("depthSampler", _this._depthTexture);
  53604. if (_this._firstUpdate) {
  53605. effect.setArray("samplerOffsets", samplerOffsets);
  53606. }
  53607. };
  53608. 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");
  53609. this._blurVPostProcess.onApply = function (effect) {
  53610. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53611. effect.setTexture("depthSampler", _this._depthTexture);
  53612. if (_this._firstUpdate) {
  53613. effect.setArray("samplerOffsets", samplerOffsets);
  53614. _this._firstUpdate = false;
  53615. }
  53616. };
  53617. };
  53618. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53619. var _this = this;
  53620. var numSamples = 16;
  53621. var sampleSphere = [
  53622. 0.5381, 0.1856, -0.4319,
  53623. 0.1379, 0.2486, 0.4430,
  53624. 0.3371, 0.5679, -0.0057,
  53625. -0.6999, -0.0451, -0.0019,
  53626. 0.0689, -0.1598, -0.8547,
  53627. 0.0560, 0.0069, -0.1843,
  53628. -0.0146, 0.1402, 0.0762,
  53629. 0.0100, -0.1924, -0.0344,
  53630. -0.3577, -0.5301, -0.4358,
  53631. -0.3169, 0.1063, 0.0158,
  53632. 0.0103, -0.5869, 0.0046,
  53633. -0.0897, -0.4940, 0.3287,
  53634. 0.7119, -0.0154, -0.0918,
  53635. -0.0533, 0.0596, -0.5411,
  53636. 0.0352, -0.0631, 0.5460,
  53637. -0.4776, 0.2847, -0.0271
  53638. ];
  53639. var samplesFactor = 1.0 / numSamples;
  53640. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53641. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53642. "area", "fallOff", "base", "range", "viewport"
  53643. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53644. var viewport = new BABYLON.Vector2(0, 0);
  53645. this._ssaoPostProcess.onApply = function (effect) {
  53646. if (_this._firstUpdate) {
  53647. effect.setArray3("sampleSphere", sampleSphere);
  53648. effect.setFloat("samplesFactor", samplesFactor);
  53649. effect.setFloat("randTextureTiles", 4.0);
  53650. }
  53651. effect.setFloat("totalStrength", _this.totalStrength);
  53652. effect.setFloat("radius", _this.radius);
  53653. effect.setFloat("area", _this.area);
  53654. effect.setFloat("fallOff", _this.fallOff);
  53655. effect.setFloat("base", _this.base);
  53656. effect.setTexture("textureSampler", _this._depthTexture);
  53657. effect.setTexture("randomSampler", _this._randomTexture);
  53658. };
  53659. };
  53660. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53661. var _this = this;
  53662. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53663. this._ssaoCombinePostProcess.onApply = function (effect) {
  53664. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53665. };
  53666. };
  53667. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53668. var size = 512;
  53669. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53670. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53671. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53672. var context = this._randomTexture.getContext();
  53673. var rand = function (min, max) {
  53674. return Math.random() * (max - min) + min;
  53675. };
  53676. var randVector = BABYLON.Vector3.Zero();
  53677. for (var x = 0; x < size; x++) {
  53678. for (var y = 0; y < size; y++) {
  53679. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53680. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53681. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53682. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53683. context.fillRect(x, y, 1, 1);
  53684. }
  53685. }
  53686. this._randomTexture.update(false);
  53687. };
  53688. __decorate([
  53689. BABYLON.serialize()
  53690. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53691. __decorate([
  53692. BABYLON.serialize()
  53693. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53694. __decorate([
  53695. BABYLON.serialize()
  53696. ], SSAORenderingPipeline.prototype, "area", void 0);
  53697. __decorate([
  53698. BABYLON.serialize()
  53699. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53700. __decorate([
  53701. BABYLON.serialize()
  53702. ], SSAORenderingPipeline.prototype, "base", void 0);
  53703. __decorate([
  53704. BABYLON.serialize()
  53705. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53706. return SSAORenderingPipeline;
  53707. })(BABYLON.PostProcessRenderPipeline);
  53708. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53709. })(BABYLON || (BABYLON = {}));
  53710. var BABYLON;
  53711. (function (BABYLON) {
  53712. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  53713. var VolumetricLightScatteringPostProcess = (function (_super) {
  53714. __extends(VolumetricLightScatteringPostProcess, _super);
  53715. /**
  53716. * @constructor
  53717. * @param {string} name - The post-process name
  53718. * @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)
  53719. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  53720. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  53721. * @param {number} samples - The post-process quality, default 100
  53722. * @param {number} samplingMode - The post-process filtering mode
  53723. * @param {BABYLON.Engine} engine - The babylon engine
  53724. * @param {boolean} reusable - If the post-process is reusable
  53725. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  53726. */
  53727. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  53728. var _this = this;
  53729. if (samples === void 0) { samples = 100; }
  53730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53731. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  53732. this._screenCoordinates = BABYLON.Vector2.Zero();
  53733. /**
  53734. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  53735. * @type {Vector3}
  53736. */
  53737. this.customMeshPosition = BABYLON.Vector3.Zero();
  53738. /**
  53739. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  53740. * @type {boolean}
  53741. */
  53742. this.useCustomMeshPosition = false;
  53743. /**
  53744. * If the post-process should inverse the light scattering direction
  53745. * @type {boolean}
  53746. */
  53747. this.invert = true;
  53748. /**
  53749. * Array containing the excluded meshes not rendered in the internal pass
  53750. */
  53751. this.excludedMeshes = new Array();
  53752. /**
  53753. * Controls the overall intensity of the post-process
  53754. * @type {number}
  53755. */
  53756. this.exposure = 0.3;
  53757. /**
  53758. * Dissipates each sample's contribution in range [0, 1]
  53759. * @type {number}
  53760. */
  53761. this.decay = 0.96815;
  53762. /**
  53763. * Controls the overall intensity of each sample
  53764. * @type {number}
  53765. */
  53766. this.weight = 0.58767;
  53767. /**
  53768. * Controls the density of each sample
  53769. * @type {number}
  53770. */
  53771. this.density = 0.926;
  53772. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  53773. var engine = scene.getEngine();
  53774. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  53775. // Configure mesh
  53776. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  53777. // Configure
  53778. this._createPass(scene, ratio.passRatio || ratio);
  53779. this.onActivate = function (camera) {
  53780. if (!_this.isSupported) {
  53781. _this.dispose(camera);
  53782. }
  53783. _this.onActivate = null;
  53784. };
  53785. this.onApplyObservable.add(function (effect) {
  53786. _this._updateMeshScreenCoordinates(scene);
  53787. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  53788. effect.setFloat("exposure", _this.exposure);
  53789. effect.setFloat("decay", _this.decay);
  53790. effect.setFloat("weight", _this.weight);
  53791. effect.setFloat("density", _this.density);
  53792. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  53793. });
  53794. }
  53795. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  53796. get: function () {
  53797. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53798. return false;
  53799. },
  53800. set: function (useDiffuseColor) {
  53801. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  53802. },
  53803. enumerable: true,
  53804. configurable: true
  53805. });
  53806. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  53807. var mesh = subMesh.getMesh();
  53808. // Render this.mesh as default
  53809. if (mesh === this.mesh) {
  53810. return mesh.material.isReady(mesh);
  53811. }
  53812. var defines = [];
  53813. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53814. var material = subMesh.getMaterial();
  53815. var needUV = false;
  53816. // Alpha test
  53817. if (material) {
  53818. if (material.needAlphaTesting()) {
  53819. defines.push("#define ALPHATEST");
  53820. }
  53821. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53822. attribs.push(BABYLON.VertexBuffer.UVKind);
  53823. defines.push("#define UV1");
  53824. }
  53825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53826. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53827. defines.push("#define UV2");
  53828. }
  53829. }
  53830. // Bones
  53831. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53832. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53833. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53834. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53835. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53836. }
  53837. else {
  53838. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53839. }
  53840. // Instances
  53841. if (useInstances) {
  53842. defines.push("#define INSTANCES");
  53843. attribs.push("world0");
  53844. attribs.push("world1");
  53845. attribs.push("world2");
  53846. attribs.push("world3");
  53847. }
  53848. // Get correct effect
  53849. var join = defines.join("\n");
  53850. if (this._cachedDefines !== join) {
  53851. this._cachedDefines = join;
  53852. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  53853. }
  53854. return this._volumetricLightScatteringPass.isReady();
  53855. };
  53856. /**
  53857. * Sets the new light position for light scattering effect
  53858. * @param {BABYLON.Vector3} The new custom light position
  53859. */
  53860. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  53861. this.customMeshPosition = position;
  53862. };
  53863. /**
  53864. * Returns the light position for light scattering effect
  53865. * @return {BABYLON.Vector3} The custom light position
  53866. */
  53867. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  53868. return this.customMeshPosition;
  53869. };
  53870. /**
  53871. * Disposes the internal assets and detaches the post-process from the camera
  53872. */
  53873. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  53874. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  53875. if (rttIndex !== -1) {
  53876. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  53877. }
  53878. this._volumetricLightScatteringRTT.dispose();
  53879. _super.prototype.dispose.call(this, camera);
  53880. };
  53881. /**
  53882. * Returns the render target texture used by the post-process
  53883. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  53884. */
  53885. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  53886. return this._volumetricLightScatteringRTT;
  53887. };
  53888. // Private methods
  53889. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  53890. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  53891. return true;
  53892. }
  53893. return false;
  53894. };
  53895. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  53896. var _this = this;
  53897. var engine = scene.getEngine();
  53898. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53899. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53900. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53901. this._volumetricLightScatteringRTT.renderList = null;
  53902. this._volumetricLightScatteringRTT.renderParticles = false;
  53903. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  53904. // Custom render function for submeshes
  53905. var renderSubMesh = function (subMesh) {
  53906. var mesh = subMesh.getRenderingMesh();
  53907. if (_this._meshExcluded(mesh)) {
  53908. return;
  53909. }
  53910. var scene = mesh.getScene();
  53911. var engine = scene.getEngine();
  53912. // Culling
  53913. engine.setState(subMesh.getMaterial().backFaceCulling);
  53914. // Managing instances
  53915. var batch = mesh._getInstancesRenderList(subMesh._id);
  53916. if (batch.mustReturn) {
  53917. return;
  53918. }
  53919. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  53920. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  53921. var effect = _this._volumetricLightScatteringPass;
  53922. if (mesh === _this.mesh) {
  53923. effect = subMesh.getMaterial().getEffect();
  53924. }
  53925. engine.enableEffect(effect);
  53926. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  53927. if (mesh === _this.mesh) {
  53928. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  53929. }
  53930. else {
  53931. var material = subMesh.getMaterial();
  53932. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  53933. // Alpha test
  53934. if (material && material.needAlphaTesting()) {
  53935. var alphaTexture = material.getAlphaTestTexture();
  53936. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  53937. if (alphaTexture) {
  53938. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  53939. }
  53940. }
  53941. // Bones
  53942. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53943. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  53944. }
  53945. }
  53946. // Draw
  53947. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  53948. }
  53949. };
  53950. // Render target texture callbacks
  53951. var savedSceneClearColor;
  53952. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  53953. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  53954. savedSceneClearColor = scene.clearColor;
  53955. scene.clearColor = sceneClearColor;
  53956. });
  53957. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  53958. scene.clearColor = savedSceneClearColor;
  53959. });
  53960. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  53961. var engine = scene.getEngine();
  53962. var index;
  53963. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53964. renderSubMesh(opaqueSubMeshes.data[index]);
  53965. }
  53966. engine.setAlphaTesting(true);
  53967. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53968. renderSubMesh(alphaTestSubMeshes.data[index]);
  53969. }
  53970. engine.setAlphaTesting(false);
  53971. if (transparentSubMeshes.length) {
  53972. // Sort sub meshes
  53973. for (index = 0; index < transparentSubMeshes.length; index++) {
  53974. var submesh = transparentSubMeshes.data[index];
  53975. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  53976. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  53977. }
  53978. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  53979. sortedArray.sort(function (a, b) {
  53980. // Alpha index first
  53981. if (a._alphaIndex > b._alphaIndex) {
  53982. return 1;
  53983. }
  53984. if (a._alphaIndex < b._alphaIndex) {
  53985. return -1;
  53986. }
  53987. // Then distance to camera
  53988. if (a._distanceToCamera < b._distanceToCamera) {
  53989. return 1;
  53990. }
  53991. if (a._distanceToCamera > b._distanceToCamera) {
  53992. return -1;
  53993. }
  53994. return 0;
  53995. });
  53996. // Render sub meshes
  53997. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53998. for (index = 0; index < sortedArray.length; index++) {
  53999. renderSubMesh(sortedArray[index]);
  54000. }
  54001. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54002. }
  54003. };
  54004. };
  54005. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54006. var transform = scene.getTransformMatrix();
  54007. var meshPosition;
  54008. if (this.useCustomMeshPosition) {
  54009. meshPosition = this.customMeshPosition;
  54010. }
  54011. else if (this.attachedNode) {
  54012. meshPosition = this.attachedNode.position;
  54013. }
  54014. else {
  54015. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54016. }
  54017. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54018. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54019. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54020. if (this.invert)
  54021. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54022. };
  54023. // Static methods
  54024. /**
  54025. * Creates a default mesh for the Volumeric Light Scattering post-process
  54026. * @param {string} The mesh name
  54027. * @param {BABYLON.Scene} The scene where to create the mesh
  54028. * @return {BABYLON.Mesh} the default mesh
  54029. */
  54030. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54031. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54032. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54033. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54034. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54035. mesh.material = material;
  54036. return mesh;
  54037. };
  54038. __decorate([
  54039. BABYLON.serializeAsVector3()
  54040. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54041. __decorate([
  54042. BABYLON.serialize()
  54043. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54044. __decorate([
  54045. BABYLON.serialize()
  54046. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54047. __decorate([
  54048. BABYLON.serializeAsMeshReference()
  54049. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54050. __decorate([
  54051. BABYLON.serialize()
  54052. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54053. __decorate([
  54054. BABYLON.serialize()
  54055. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54056. __decorate([
  54057. BABYLON.serialize()
  54058. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54059. __decorate([
  54060. BABYLON.serialize()
  54061. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54062. __decorate([
  54063. BABYLON.serialize()
  54064. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54065. return VolumetricLightScatteringPostProcess;
  54066. })(BABYLON.PostProcess);
  54067. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54068. })(BABYLON || (BABYLON = {}));
  54069. // BABYLON.JS Chromatic Aberration GLSL Shader
  54070. // Author: Olivier Guyot
  54071. // Separates very slightly R, G and B colors on the edges of the screen
  54072. // Inspired by Francois Tarlier & Martins Upitis
  54073. var BABYLON;
  54074. (function (BABYLON) {
  54075. var LensRenderingPipeline = (function (_super) {
  54076. __extends(LensRenderingPipeline, _super);
  54077. /**
  54078. * @constructor
  54079. *
  54080. * Effect parameters are as follow:
  54081. * {
  54082. * chromatic_aberration: number; // from 0 to x (1 for realism)
  54083. * edge_blur: number; // from 0 to x (1 for realism)
  54084. * distortion: number; // from 0 to x (1 for realism)
  54085. * grain_amount: number; // from 0 to 1
  54086. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  54087. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  54088. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  54089. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  54090. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  54091. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  54092. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  54093. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  54094. * }
  54095. * Note: if an effect parameter is unset, effect is disabled
  54096. *
  54097. * @param {string} name - The rendering pipeline name
  54098. * @param {object} parameters - An object containing all parameters (see above)
  54099. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54100. * @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)
  54101. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54102. */
  54103. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  54104. var _this = this;
  54105. if (ratio === void 0) { ratio = 1.0; }
  54106. _super.call(this, scene.getEngine(), name);
  54107. // Lens effects can be of the following:
  54108. // - chromatic aberration (slight shift of RGB colors)
  54109. // - blur on the edge of the lens
  54110. // - lens distortion
  54111. // - depth-of-field blur & highlights enhancing
  54112. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  54113. // - grain effect (noise or custom texture)
  54114. // Two additional texture samplers are needed:
  54115. // - depth map (for depth-of-field)
  54116. // - grain texture
  54117. /**
  54118. * The chromatic aberration PostProcess id in the pipeline
  54119. * @type {string}
  54120. */
  54121. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  54122. /**
  54123. * The highlights enhancing PostProcess id in the pipeline
  54124. * @type {string}
  54125. */
  54126. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  54127. /**
  54128. * The depth-of-field PostProcess id in the pipeline
  54129. * @type {string}
  54130. */
  54131. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  54132. this._scene = scene;
  54133. // Fetch texture samplers
  54134. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  54135. if (parameters.grain_texture) {
  54136. this._grainTexture = parameters.grain_texture;
  54137. }
  54138. else {
  54139. this._createGrainTexture();
  54140. }
  54141. // save parameters
  54142. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  54143. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  54144. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  54145. this._distortion = parameters.distortion ? parameters.distortion : 0;
  54146. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  54147. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  54148. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  54149. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  54150. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  54151. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  54152. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  54153. // Create effects
  54154. this._createChromaticAberrationPostProcess(ratio);
  54155. this._createHighlightsPostProcess(ratio);
  54156. this._createDepthOfFieldPostProcess(ratio / 4);
  54157. // Set up pipeline
  54158. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  54159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  54160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  54161. if (this._highlightsGain === -1) {
  54162. this._disableEffect(this.HighlightsEnhancingEffect, null);
  54163. }
  54164. // Finish
  54165. scene.postProcessRenderPipelineManager.addPipeline(this);
  54166. if (cameras) {
  54167. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54168. }
  54169. }
  54170. // public methods (self explanatory)
  54171. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  54172. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  54173. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  54174. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  54175. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  54176. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  54177. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  54178. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  54179. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  54180. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  54181. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  54182. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  54183. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  54184. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  54185. };
  54186. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  54187. this._highlightsPostProcess.updateEffect();
  54188. };
  54189. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  54190. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  54191. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  54192. this._highlightsGain = amount;
  54193. };
  54194. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  54195. if (this._highlightsGain === -1) {
  54196. this._highlightsGain = 1.0;
  54197. }
  54198. this._highlightsThreshold = amount;
  54199. };
  54200. LensRenderingPipeline.prototype.disableHighlights = function () {
  54201. this._highlightsGain = -1;
  54202. };
  54203. /**
  54204. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  54205. */
  54206. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  54207. if (disableDepthRender === void 0) { disableDepthRender = false; }
  54208. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54209. this._chromaticAberrationPostProcess = undefined;
  54210. this._highlightsPostProcess = undefined;
  54211. this._depthOfFieldPostProcess = undefined;
  54212. this._grainTexture.dispose();
  54213. if (disableDepthRender)
  54214. this._scene.disableDepthRenderer();
  54215. };
  54216. // colors shifting and distortion
  54217. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  54218. var _this = this;
  54219. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  54220. [], // samplers
  54221. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54222. this._chromaticAberrationPostProcess.onApply = function (effect) {
  54223. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  54224. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54225. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54226. };
  54227. };
  54228. // highlights enhancing
  54229. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  54230. var _this = this;
  54231. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  54232. [], // samplers
  54233. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  54234. this._highlightsPostProcess.onApply = function (effect) {
  54235. effect.setFloat('gain', _this._highlightsGain);
  54236. effect.setFloat('threshold', _this._highlightsThreshold);
  54237. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  54238. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54239. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54240. };
  54241. };
  54242. // colors shifting and distortion
  54243. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  54244. var _this = this;
  54245. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  54246. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  54247. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  54248. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  54249. this._depthOfFieldPostProcess.onApply = function (effect) {
  54250. effect.setTexture("depthSampler", _this._depthTexture);
  54251. effect.setTexture("grainSampler", _this._grainTexture);
  54252. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  54253. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  54254. effect.setFloat('grain_amount', _this._grainAmount);
  54255. effect.setBool('blur_noise', _this._blurNoise);
  54256. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  54257. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  54258. effect.setFloat('distortion', _this._distortion);
  54259. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  54260. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  54261. effect.setFloat('aperture', _this._dofAperture);
  54262. effect.setFloat('darken', _this._dofDarken);
  54263. effect.setFloat('edge_blur', _this._edgeBlur);
  54264. effect.setBool('highlights', (_this._highlightsGain !== -1));
  54265. effect.setFloat('near', _this._scene.activeCamera.minZ);
  54266. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  54267. };
  54268. };
  54269. // creates a black and white random noise texture, 512x512
  54270. LensRenderingPipeline.prototype._createGrainTexture = function () {
  54271. var size = 512;
  54272. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54273. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54274. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54275. var context = this._grainTexture.getContext();
  54276. var rand = function (min, max) {
  54277. return Math.random() * (max - min) + min;
  54278. };
  54279. var value;
  54280. for (var x = 0; x < size; x++) {
  54281. for (var y = 0; y < size; y++) {
  54282. value = Math.floor(rand(0.42, 0.58) * 255);
  54283. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  54284. context.fillRect(x, y, 1, 1);
  54285. }
  54286. }
  54287. this._grainTexture.update(false);
  54288. };
  54289. return LensRenderingPipeline;
  54290. })(BABYLON.PostProcessRenderPipeline);
  54291. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  54292. })(BABYLON || (BABYLON = {}));
  54293. //
  54294. // This post-process allows the modification of rendered colors by using
  54295. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54296. //
  54297. // The object needs to be provided an url to a texture containing the color
  54298. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54299. // Use an image editing software to tweak the LUT to match your needs.
  54300. //
  54301. // For an example of a color LUT, see here:
  54302. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54303. // For explanations on color grading, see here:
  54304. // http://udn.epicgames.com/Three/ColorGrading.html
  54305. //
  54306. var BABYLON;
  54307. (function (BABYLON) {
  54308. var ColorCorrectionPostProcess = (function (_super) {
  54309. __extends(ColorCorrectionPostProcess, _super);
  54310. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54311. var _this = this;
  54312. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  54313. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54314. this._colorTableTexture.anisotropicFilteringLevel = 1;
  54315. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54316. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54317. this.onApply = function (effect) {
  54318. effect.setTexture("colorTable", _this._colorTableTexture);
  54319. };
  54320. }
  54321. return ColorCorrectionPostProcess;
  54322. })(BABYLON.PostProcess);
  54323. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54324. })(BABYLON || (BABYLON = {}));
  54325. var BABYLON;
  54326. (function (BABYLON) {
  54327. var AnaglyphFreeCamera = (function (_super) {
  54328. __extends(AnaglyphFreeCamera, _super);
  54329. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  54330. _super.call(this, name, position, scene);
  54331. this.interaxialDistance = interaxialDistance;
  54332. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54333. }
  54334. AnaglyphFreeCamera.prototype.getTypeName = function () {
  54335. return "AnaglyphFreeCamera";
  54336. };
  54337. return AnaglyphFreeCamera;
  54338. })(BABYLON.FreeCamera);
  54339. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  54340. var AnaglyphArcRotateCamera = (function (_super) {
  54341. __extends(AnaglyphArcRotateCamera, _super);
  54342. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  54343. _super.call(this, name, alpha, beta, radius, target, scene);
  54344. this.interaxialDistance = interaxialDistance;
  54345. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54346. }
  54347. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  54348. return "AnaglyphArcRotateCamera";
  54349. };
  54350. return AnaglyphArcRotateCamera;
  54351. })(BABYLON.ArcRotateCamera);
  54352. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  54353. var AnaglyphGamepadCamera = (function (_super) {
  54354. __extends(AnaglyphGamepadCamera, _super);
  54355. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  54356. _super.call(this, name, position, scene);
  54357. this.interaxialDistance = interaxialDistance;
  54358. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54359. }
  54360. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  54361. return "AnaglyphGamepadCamera";
  54362. };
  54363. return AnaglyphGamepadCamera;
  54364. })(BABYLON.GamepadCamera);
  54365. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  54366. var AnaglyphUniversalCamera = (function (_super) {
  54367. __extends(AnaglyphUniversalCamera, _super);
  54368. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  54369. _super.call(this, name, position, scene);
  54370. this.interaxialDistance = interaxialDistance;
  54371. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  54372. }
  54373. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  54374. return "AnaglyphUniversalCamera";
  54375. };
  54376. return AnaglyphUniversalCamera;
  54377. })(BABYLON.UniversalCamera);
  54378. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  54379. var StereoscopicFreeCamera = (function (_super) {
  54380. __extends(StereoscopicFreeCamera, _super);
  54381. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54382. _super.call(this, name, position, scene);
  54383. this.interaxialDistance = interaxialDistance;
  54384. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54385. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54386. }
  54387. StereoscopicFreeCamera.prototype.getTypeName = function () {
  54388. return "StereoscopicFreeCamera";
  54389. };
  54390. return StereoscopicFreeCamera;
  54391. })(BABYLON.FreeCamera);
  54392. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  54393. var StereoscopicArcRotateCamera = (function (_super) {
  54394. __extends(StereoscopicArcRotateCamera, _super);
  54395. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  54396. _super.call(this, name, alpha, beta, radius, target, scene);
  54397. this.interaxialDistance = interaxialDistance;
  54398. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54399. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54400. }
  54401. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  54402. return "StereoscopicArcRotateCamera";
  54403. };
  54404. return StereoscopicArcRotateCamera;
  54405. })(BABYLON.ArcRotateCamera);
  54406. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  54407. var StereoscopicGamepadCamera = (function (_super) {
  54408. __extends(StereoscopicGamepadCamera, _super);
  54409. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54410. _super.call(this, name, position, scene);
  54411. this.interaxialDistance = interaxialDistance;
  54412. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54413. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54414. }
  54415. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  54416. return "StereoscopicGamepadCamera";
  54417. };
  54418. return StereoscopicGamepadCamera;
  54419. })(BABYLON.GamepadCamera);
  54420. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  54421. var StereoscopicUniversalCamera = (function (_super) {
  54422. __extends(StereoscopicUniversalCamera, _super);
  54423. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  54424. _super.call(this, name, position, scene);
  54425. this.interaxialDistance = interaxialDistance;
  54426. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  54427. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  54428. }
  54429. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  54430. return "StereoscopicUniversalCamera";
  54431. };
  54432. return StereoscopicUniversalCamera;
  54433. })(BABYLON.UniversalCamera);
  54434. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  54435. })(BABYLON || (BABYLON = {}));
  54436. var BABYLON;
  54437. (function (BABYLON) {
  54438. var HDRRenderingPipeline = (function (_super) {
  54439. __extends(HDRRenderingPipeline, _super);
  54440. /**
  54441. * @constructor
  54442. * @param {string} name - The rendering pipeline name
  54443. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54444. * @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)
  54445. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54446. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54447. */
  54448. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54449. var _this = this;
  54450. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54451. _super.call(this, scene.getEngine(), name);
  54452. /**
  54453. * Public members
  54454. */
  54455. // Gaussian Blur
  54456. /**
  54457. * Gaussian blur coefficient
  54458. * @type {number}
  54459. */
  54460. this.gaussCoeff = 0.3;
  54461. /**
  54462. * Gaussian blur mean
  54463. * @type {number}
  54464. */
  54465. this.gaussMean = 1.0;
  54466. /**
  54467. * Gaussian blur standard deviation
  54468. * @type {number}
  54469. */
  54470. this.gaussStandDev = 0.8;
  54471. /**
  54472. * Gaussian blur multiplier. Multiplies the blur effect
  54473. * @type {number}
  54474. */
  54475. this.gaussMultiplier = 4.0;
  54476. // HDR
  54477. /**
  54478. * Exposure, controls the overall intensity of the pipeline
  54479. * @type {number}
  54480. */
  54481. this.exposure = 1.0;
  54482. /**
  54483. * Minimum luminance that the post-process can output. Luminance is >= 0
  54484. * @type {number}
  54485. */
  54486. this.minimumLuminance = 1.0;
  54487. /**
  54488. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  54489. * @type {number}
  54490. */
  54491. this.maximumLuminance = 1e20;
  54492. /**
  54493. * Increase rate for luminance: eye adaptation speed to dark
  54494. * @type {number}
  54495. */
  54496. this.luminanceIncreaserate = 0.5;
  54497. /**
  54498. * Decrease rate for luminance: eye adaptation speed to bright
  54499. * @type {number}
  54500. */
  54501. this.luminanceDecreaseRate = 0.5;
  54502. // Bright pass
  54503. /**
  54504. * Minimum luminance needed to compute HDR
  54505. * @type {number}
  54506. */
  54507. this.brightThreshold = 0.8;
  54508. this._needUpdate = true;
  54509. this._scene = scene;
  54510. // Bright pass
  54511. this._createBrightPassPostProcess(scene, ratio);
  54512. // Down sample X4
  54513. this._createDownSampleX4PostProcess(scene, ratio);
  54514. // Create gaussian blur post-processes
  54515. this._createGaussianBlurPostProcess(scene, ratio);
  54516. // Texture adder
  54517. this._createTextureAdderPostProcess(scene, ratio);
  54518. // Luminance generator
  54519. this._createLuminanceGeneratorPostProcess(scene);
  54520. // HDR
  54521. this._createHDRPostProcess(scene, ratio);
  54522. // Pass postprocess
  54523. if (originalPostProcess === null) {
  54524. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  54525. }
  54526. else {
  54527. this._originalPostProcess = originalPostProcess;
  54528. }
  54529. // Configure pipeline
  54530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  54531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  54532. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  54533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  54534. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  54535. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  54536. var addDownSamplerPostProcess = function (id) {
  54537. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  54538. };
  54539. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54540. addDownSamplerPostProcess(i);
  54541. }
  54542. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  54543. // Finish
  54544. scene.postProcessRenderPipelineManager.addPipeline(this);
  54545. if (cameras !== null) {
  54546. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54547. }
  54548. this.update();
  54549. }
  54550. /**
  54551. * Tells the pipeline to update its post-processes
  54552. */
  54553. HDRRenderingPipeline.prototype.update = function () {
  54554. this._needUpdate = true;
  54555. };
  54556. /**
  54557. * Returns the current calculated luminance
  54558. */
  54559. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  54560. return this._hdrCurrentLuminance;
  54561. };
  54562. /**
  54563. * Returns the currently drawn luminance
  54564. */
  54565. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  54566. return this._hdrOutputLuminance;
  54567. };
  54568. /**
  54569. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  54570. */
  54571. HDRRenderingPipeline.prototype.dispose = function () {
  54572. this._originalPostProcess = undefined;
  54573. this._brightPassPostProcess = undefined;
  54574. this._downSampleX4PostProcess = undefined;
  54575. this._guassianBlurHPostProcess = undefined;
  54576. this._guassianBlurVPostProcess = undefined;
  54577. this._textureAdderPostProcess = undefined;
  54578. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  54579. this._downSamplePostProcesses[i] = undefined;
  54580. }
  54581. this._hdrPostProcess = undefined;
  54582. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54583. };
  54584. /**
  54585. * Creates the HDR post-process and computes the luminance adaptation
  54586. */
  54587. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  54588. var _this = this;
  54589. var hdrLastLuminance = 0.0;
  54590. this._hdrOutputLuminance = -1.0;
  54591. this._hdrCurrentLuminance = 1.0;
  54592. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  54593. this._hdrPostProcess.onApply = function (effect) {
  54594. if (_this._hdrOutputLuminance < 0.0) {
  54595. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54596. }
  54597. else {
  54598. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  54599. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  54600. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  54601. }
  54602. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  54603. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  54604. }
  54605. else {
  54606. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  54607. }
  54608. }
  54609. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  54610. hdrLastLuminance += scene.getEngine().getDeltaTime();
  54611. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54612. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54613. effect.setFloat("exposure", _this.exposure);
  54614. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  54615. _this._needUpdate = false;
  54616. };
  54617. };
  54618. /**
  54619. * Texture Adder post-process
  54620. */
  54621. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54622. var _this = this;
  54623. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  54624. this._textureAdderPostProcess.onApply = function (effect) {
  54625. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  54626. };
  54627. };
  54628. /**
  54629. * Down sample X4 post-process
  54630. */
  54631. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54632. var _this = this;
  54633. var downSampleX4Offsets = new Array(32);
  54634. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  54635. this._downSampleX4PostProcess.onApply = function (effect) {
  54636. if (_this._needUpdate) {
  54637. var id = 0;
  54638. for (var i = -2; i < 2; i++) {
  54639. for (var j = -2; j < 2; j++) {
  54640. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  54641. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  54642. id += 2;
  54643. }
  54644. }
  54645. }
  54646. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54647. };
  54648. };
  54649. /**
  54650. * Bright pass post-process
  54651. */
  54652. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54653. var _this = this;
  54654. var brightOffsets = new Array(8);
  54655. var brightPassCallback = function (effect) {
  54656. if (_this._needUpdate) {
  54657. var sU = (1.0 / _this._brightPassPostProcess.width);
  54658. var sV = (1.0 / _this._brightPassPostProcess.height);
  54659. brightOffsets[0] = -0.5 * sU;
  54660. brightOffsets[1] = 0.5 * sV;
  54661. brightOffsets[2] = 0.5 * sU;
  54662. brightOffsets[3] = 0.5 * sV;
  54663. brightOffsets[4] = -0.5 * sU;
  54664. brightOffsets[5] = -0.5 * sV;
  54665. brightOffsets[6] = 0.5 * sU;
  54666. brightOffsets[7] = -0.5 * sV;
  54667. }
  54668. effect.setArray2("dsOffsets", brightOffsets);
  54669. effect.setFloat("brightThreshold", _this.brightThreshold);
  54670. };
  54671. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  54672. this._brightPassPostProcess.onApply = brightPassCallback;
  54673. };
  54674. /**
  54675. * Luminance generator. Creates the luminance post-process and down sample post-processes
  54676. */
  54677. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  54678. var _this = this;
  54679. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  54680. var luminanceOffsets = new Array(8);
  54681. var downSampleOffsets = new Array(18);
  54682. var halfDestPixelSize;
  54683. this._downSamplePostProcesses = new Array(lumSteps);
  54684. // Utils for luminance
  54685. var luminanceUpdateSourceOffsets = function (width, height) {
  54686. var sU = (1.0 / width);
  54687. var sV = (1.0 / height);
  54688. luminanceOffsets[0] = -0.5 * sU;
  54689. luminanceOffsets[1] = 0.5 * sV;
  54690. luminanceOffsets[2] = 0.5 * sU;
  54691. luminanceOffsets[3] = 0.5 * sV;
  54692. luminanceOffsets[4] = -0.5 * sU;
  54693. luminanceOffsets[5] = -0.5 * sV;
  54694. luminanceOffsets[6] = 0.5 * sU;
  54695. luminanceOffsets[7] = -0.5 * sV;
  54696. };
  54697. var luminanceUpdateDestOffsets = function (width, height) {
  54698. var id = 0;
  54699. for (var x = -1; x < 2; x++) {
  54700. for (var y = -1; y < 2; y++) {
  54701. downSampleOffsets[id] = (x) / width;
  54702. downSampleOffsets[id + 1] = (y) / height;
  54703. id += 2;
  54704. }
  54705. }
  54706. };
  54707. // Luminance callback
  54708. var luminanceCallback = function (effect) {
  54709. if (_this._needUpdate) {
  54710. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  54711. }
  54712. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  54713. effect.setArray2("lumOffsets", luminanceOffsets);
  54714. };
  54715. // Down sample callbacks
  54716. var downSampleCallback = function (indice) {
  54717. var i = indice;
  54718. return function (effect) {
  54719. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54720. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  54721. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  54722. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  54723. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  54724. effect.setArray2("dsOffsets", downSampleOffsets);
  54725. };
  54726. };
  54727. var downSampleAfterRenderCallback = function (effect) {
  54728. // Unpack result
  54729. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54730. 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);
  54731. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54732. };
  54733. // Create luminance post-process
  54734. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  54735. 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);
  54736. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  54737. // Create down sample post-processes
  54738. for (var i = lumSteps - 2; i >= 0; i--) {
  54739. var length = Math.pow(3, i);
  54740. ratio = { width: length, height: length };
  54741. var defines = "#define DOWN_SAMPLE\n";
  54742. if (i === 0) {
  54743. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  54744. }
  54745. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  54746. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  54747. if (i === 0) {
  54748. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  54749. }
  54750. }
  54751. };
  54752. /**
  54753. * Gaussian blur post-processes. Horizontal and Vertical
  54754. */
  54755. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  54756. var _this = this;
  54757. var blurOffsetsW = new Array(9);
  54758. var blurOffsetsH = new Array(9);
  54759. var blurWeights = new Array(9);
  54760. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  54761. // Utils for gaussian blur
  54762. var calculateBlurOffsets = function (height) {
  54763. var lastOutputDimensions = {
  54764. width: scene.getEngine().getRenderWidth(),
  54765. height: scene.getEngine().getRenderHeight()
  54766. };
  54767. for (var i = 0; i < 9; i++) {
  54768. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54769. if (height) {
  54770. blurOffsetsH[i] = value;
  54771. }
  54772. else {
  54773. blurOffsetsW[i] = value;
  54774. }
  54775. }
  54776. };
  54777. var calculateWeights = function () {
  54778. var x = 0.0;
  54779. for (var i = 0; i < 9; i++) {
  54780. x = (i - 4.0) / 4.0;
  54781. 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));
  54782. }
  54783. };
  54784. // Callback
  54785. var gaussianBlurCallback = function (height) {
  54786. return function (effect) {
  54787. if (_this._needUpdate) {
  54788. calculateWeights();
  54789. calculateBlurOffsets(height);
  54790. }
  54791. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  54792. effect.setArray("blurWeights", blurWeights);
  54793. effect.setFloat("multiplier", _this.gaussMultiplier);
  54794. };
  54795. };
  54796. // Create horizontal gaussian blur post-processes
  54797. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  54798. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  54799. // Create vertical gaussian blur post-process
  54800. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  54801. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  54802. };
  54803. // Luminance generator
  54804. HDRRenderingPipeline.LUM_STEPS = 6;
  54805. return HDRRenderingPipeline;
  54806. })(BABYLON.PostProcessRenderPipeline);
  54807. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  54808. })(BABYLON || (BABYLON = {}));
  54809. var BABYLON;
  54810. (function (BABYLON) {
  54811. var FaceAdjacencies = (function () {
  54812. function FaceAdjacencies() {
  54813. this.edges = new Array();
  54814. this.edgesConnectedCount = 0;
  54815. }
  54816. return FaceAdjacencies;
  54817. })();
  54818. var EdgesRenderer = (function () {
  54819. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  54820. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  54821. if (epsilon === void 0) { epsilon = 0.95; }
  54822. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  54823. this.edgesWidthScalerForOrthographic = 1000.0;
  54824. this.edgesWidthScalerForPerspective = 50.0;
  54825. this._linesPositions = new Array();
  54826. this._linesNormals = new Array();
  54827. this._linesIndices = new Array();
  54828. this._buffers = {};
  54829. this._checkVerticesInsteadOfIndices = false;
  54830. this._source = source;
  54831. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  54832. this._epsilon = epsilon;
  54833. this._prepareRessources();
  54834. this._generateEdgesLines();
  54835. }
  54836. EdgesRenderer.prototype._prepareRessources = function () {
  54837. if (this._lineShader) {
  54838. return;
  54839. }
  54840. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  54841. attributes: ["position", "normal"],
  54842. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  54843. });
  54844. this._lineShader.disableDepthWrite = true;
  54845. this._lineShader.backFaceCulling = false;
  54846. };
  54847. EdgesRenderer.prototype.dispose = function () {
  54848. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  54849. if (buffer) {
  54850. buffer.dispose();
  54851. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  54852. }
  54853. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  54854. if (buffer) {
  54855. buffer.dispose();
  54856. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  54857. }
  54858. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  54859. this._lineShader.dispose();
  54860. };
  54861. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  54862. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  54863. return 0;
  54864. }
  54865. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  54866. return 1;
  54867. }
  54868. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  54869. return 2;
  54870. }
  54871. return -1;
  54872. };
  54873. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  54874. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  54875. return 0;
  54876. }
  54877. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  54878. return 1;
  54879. }
  54880. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  54881. return 2;
  54882. }
  54883. return -1;
  54884. };
  54885. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  54886. var needToCreateLine;
  54887. if (edge === undefined) {
  54888. needToCreateLine = true;
  54889. }
  54890. else {
  54891. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  54892. needToCreateLine = dotProduct < this._epsilon;
  54893. }
  54894. if (needToCreateLine) {
  54895. var offset = this._linesPositions.length / 3;
  54896. var normal = p0.subtract(p1);
  54897. normal.normalize();
  54898. // Positions
  54899. this._linesPositions.push(p0.x);
  54900. this._linesPositions.push(p0.y);
  54901. this._linesPositions.push(p0.z);
  54902. this._linesPositions.push(p0.x);
  54903. this._linesPositions.push(p0.y);
  54904. this._linesPositions.push(p0.z);
  54905. this._linesPositions.push(p1.x);
  54906. this._linesPositions.push(p1.y);
  54907. this._linesPositions.push(p1.z);
  54908. this._linesPositions.push(p1.x);
  54909. this._linesPositions.push(p1.y);
  54910. this._linesPositions.push(p1.z);
  54911. // Normals
  54912. this._linesNormals.push(p1.x);
  54913. this._linesNormals.push(p1.y);
  54914. this._linesNormals.push(p1.z);
  54915. this._linesNormals.push(-1);
  54916. this._linesNormals.push(p1.x);
  54917. this._linesNormals.push(p1.y);
  54918. this._linesNormals.push(p1.z);
  54919. this._linesNormals.push(1);
  54920. this._linesNormals.push(p0.x);
  54921. this._linesNormals.push(p0.y);
  54922. this._linesNormals.push(p0.z);
  54923. this._linesNormals.push(-1);
  54924. this._linesNormals.push(p0.x);
  54925. this._linesNormals.push(p0.y);
  54926. this._linesNormals.push(p0.z);
  54927. this._linesNormals.push(1);
  54928. // Indices
  54929. this._linesIndices.push(offset);
  54930. this._linesIndices.push(offset + 1);
  54931. this._linesIndices.push(offset + 2);
  54932. this._linesIndices.push(offset);
  54933. this._linesIndices.push(offset + 2);
  54934. this._linesIndices.push(offset + 3);
  54935. }
  54936. };
  54937. EdgesRenderer.prototype._generateEdgesLines = function () {
  54938. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54939. var indices = this._source.getIndices();
  54940. // First let's find adjacencies
  54941. var adjacencies = new Array();
  54942. var faceNormals = new Array();
  54943. var index;
  54944. var faceAdjacencies;
  54945. // Prepare faces
  54946. for (index = 0; index < indices.length; index += 3) {
  54947. faceAdjacencies = new FaceAdjacencies();
  54948. var p0Index = indices[index];
  54949. var p1Index = indices[index + 1];
  54950. var p2Index = indices[index + 2];
  54951. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  54952. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  54953. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  54954. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  54955. faceNormal.normalize();
  54956. faceNormals.push(faceNormal);
  54957. adjacencies.push(faceAdjacencies);
  54958. }
  54959. // Scan
  54960. for (index = 0; index < adjacencies.length; index++) {
  54961. faceAdjacencies = adjacencies[index];
  54962. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  54963. var otherFaceAdjacencies = adjacencies[otherIndex];
  54964. if (faceAdjacencies.edgesConnectedCount === 3) {
  54965. break;
  54966. }
  54967. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  54968. continue;
  54969. }
  54970. var otherP0 = indices[otherIndex * 3];
  54971. var otherP1 = indices[otherIndex * 3 + 1];
  54972. var otherP2 = indices[otherIndex * 3 + 2];
  54973. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  54974. var otherEdgeIndex;
  54975. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  54976. continue;
  54977. }
  54978. switch (edgeIndex) {
  54979. case 0:
  54980. if (this._checkVerticesInsteadOfIndices) {
  54981. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54982. }
  54983. else {
  54984. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  54985. }
  54986. break;
  54987. case 1:
  54988. if (this._checkVerticesInsteadOfIndices) {
  54989. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54990. }
  54991. else {
  54992. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  54993. }
  54994. break;
  54995. case 2:
  54996. if (this._checkVerticesInsteadOfIndices) {
  54997. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  54998. }
  54999. else {
  55000. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  55001. }
  55002. break;
  55003. }
  55004. if (otherEdgeIndex === -1) {
  55005. continue;
  55006. }
  55007. faceAdjacencies.edges[edgeIndex] = otherIndex;
  55008. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  55009. faceAdjacencies.edgesConnectedCount++;
  55010. otherFaceAdjacencies.edgesConnectedCount++;
  55011. if (faceAdjacencies.edgesConnectedCount === 3) {
  55012. break;
  55013. }
  55014. }
  55015. }
  55016. }
  55017. // Create lines
  55018. for (index = 0; index < adjacencies.length; index++) {
  55019. // 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
  55020. var current = adjacencies[index];
  55021. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  55022. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  55023. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  55024. }
  55025. // Merge into a single mesh
  55026. var engine = this._source.getScene().getEngine();
  55027. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  55028. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  55029. this._ib = engine.createIndexBuffer(this._linesIndices);
  55030. this._indicesCount = this._linesIndices.length;
  55031. };
  55032. EdgesRenderer.prototype.render = function () {
  55033. if (!this._lineShader.isReady()) {
  55034. return;
  55035. }
  55036. var scene = this._source.getScene();
  55037. var engine = scene.getEngine();
  55038. this._lineShader._preBind();
  55039. // VBOs
  55040. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  55041. scene.resetCachedMaterial();
  55042. this._lineShader.setColor4("color", this._source.edgesColor);
  55043. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  55044. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  55045. }
  55046. else {
  55047. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  55048. }
  55049. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  55050. this._lineShader.bind(this._source.getWorldMatrix());
  55051. // Draw order
  55052. engine.draw(true, 0, this._indicesCount);
  55053. this._lineShader.unbind();
  55054. engine.setDepthWrite(true);
  55055. };
  55056. return EdgesRenderer;
  55057. })();
  55058. BABYLON.EdgesRenderer = EdgesRenderer;
  55059. })(BABYLON || (BABYLON = {}));
  55060. var BABYLON;
  55061. (function (BABYLON) {
  55062. (function (TonemappingOperator) {
  55063. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55064. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55065. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55066. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55067. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55068. var TonemappingOperator = BABYLON.TonemappingOperator;
  55069. ;
  55070. var TonemapPostProcess = (function (_super) {
  55071. __extends(TonemapPostProcess, _super);
  55072. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55073. var _this = this;
  55074. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55075. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55076. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  55077. this._operator = _operator;
  55078. this.exposureAdjustment = exposureAdjustment;
  55079. var defines = "#define ";
  55080. if (this._operator === TonemappingOperator.Hable)
  55081. defines += "HABLE_TONEMAPPING";
  55082. else if (this._operator === TonemappingOperator.Reinhard)
  55083. defines += "REINHARD_TONEMAPPING";
  55084. else if (this._operator === TonemappingOperator.HejiDawson)
  55085. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55086. else if (this._operator === TonemappingOperator.Photographic)
  55087. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55088. //sadly a second call to create the effect.
  55089. this.updateEffect(defines);
  55090. this.onApply = function (effect) {
  55091. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55092. };
  55093. }
  55094. return TonemapPostProcess;
  55095. })(BABYLON.PostProcess);
  55096. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55097. })(BABYLON || (BABYLON = {}));
  55098. var BABYLON;
  55099. (function (BABYLON) {
  55100. var ReflectionProbe = (function () {
  55101. function ReflectionProbe(name, size, scene, generateMipMaps) {
  55102. var _this = this;
  55103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55104. this.name = name;
  55105. this._viewMatrix = BABYLON.Matrix.Identity();
  55106. this._target = BABYLON.Vector3.Zero();
  55107. this._add = BABYLON.Vector3.Zero();
  55108. this.invertYAxis = false;
  55109. this.position = BABYLON.Vector3.Zero();
  55110. this._scene = scene;
  55111. this._scene.reflectionProbes.push(this);
  55112. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  55113. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  55114. switch (faceIndex) {
  55115. case 0:
  55116. _this._add.copyFromFloats(1, 0, 0);
  55117. break;
  55118. case 1:
  55119. _this._add.copyFromFloats(-1, 0, 0);
  55120. break;
  55121. case 2:
  55122. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  55123. break;
  55124. case 3:
  55125. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  55126. break;
  55127. case 4:
  55128. _this._add.copyFromFloats(0, 0, 1);
  55129. break;
  55130. case 5:
  55131. _this._add.copyFromFloats(0, 0, -1);
  55132. break;
  55133. }
  55134. if (_this._attachedMesh) {
  55135. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  55136. }
  55137. _this.position.addToRef(_this._add, _this._target);
  55138. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  55139. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  55140. });
  55141. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  55142. scene.updateTransformMatrix(true);
  55143. });
  55144. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  55145. }
  55146. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  55147. get: function () {
  55148. return this._renderTargetTexture.refreshRate;
  55149. },
  55150. set: function (value) {
  55151. this._renderTargetTexture.refreshRate = value;
  55152. },
  55153. enumerable: true,
  55154. configurable: true
  55155. });
  55156. ReflectionProbe.prototype.getScene = function () {
  55157. return this._scene;
  55158. };
  55159. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  55160. get: function () {
  55161. return this._renderTargetTexture;
  55162. },
  55163. enumerable: true,
  55164. configurable: true
  55165. });
  55166. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  55167. get: function () {
  55168. return this._renderTargetTexture.renderList;
  55169. },
  55170. enumerable: true,
  55171. configurable: true
  55172. });
  55173. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  55174. this._attachedMesh = mesh;
  55175. };
  55176. ReflectionProbe.prototype.dispose = function () {
  55177. var index = this._scene.reflectionProbes.indexOf(this);
  55178. if (index !== -1) {
  55179. // Remove from the scene if found
  55180. this._scene.reflectionProbes.splice(index, 1);
  55181. }
  55182. if (this._renderTargetTexture) {
  55183. this._renderTargetTexture.dispose();
  55184. this._renderTargetTexture = null;
  55185. }
  55186. };
  55187. return ReflectionProbe;
  55188. })();
  55189. BABYLON.ReflectionProbe = ReflectionProbe;
  55190. })(BABYLON || (BABYLON = {}));
  55191. var BABYLON;
  55192. (function (BABYLON) {
  55193. var SolidParticle = (function () {
  55194. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  55195. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  55196. this.position = BABYLON.Vector3.Zero(); // position
  55197. this.rotation = BABYLON.Vector3.Zero(); // rotation
  55198. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  55199. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  55200. this.velocity = BABYLON.Vector3.Zero(); // velocity
  55201. this.alive = true; // alive
  55202. this.isVisible = true; // visibility
  55203. this.idx = particleIndex;
  55204. this._pos = positionIndex;
  55205. this._model = model;
  55206. this.shapeId = shapeId;
  55207. this.idxInShape = idxInShape;
  55208. }
  55209. Object.defineProperty(SolidParticle.prototype, "scale", {
  55210. //legacy support, changed scale to scaling
  55211. get: function () {
  55212. return this.scaling;
  55213. },
  55214. set: function (scale) {
  55215. this.scaling = scale;
  55216. },
  55217. enumerable: true,
  55218. configurable: true
  55219. });
  55220. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  55221. //legacy support, changed quaternion to rotationQuaternion
  55222. get: function () {
  55223. return this.rotationQuaternion;
  55224. },
  55225. set: function (q) {
  55226. this.rotationQuaternion = q;
  55227. },
  55228. enumerable: true,
  55229. configurable: true
  55230. });
  55231. return SolidParticle;
  55232. })();
  55233. BABYLON.SolidParticle = SolidParticle;
  55234. var ModelShape = (function () {
  55235. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  55236. this.shapeID = id;
  55237. this._shape = shape;
  55238. this._shapeUV = shapeUV;
  55239. this._positionFunction = posFunction;
  55240. this._vertexFunction = vtxFunction;
  55241. }
  55242. return ModelShape;
  55243. })();
  55244. BABYLON.ModelShape = ModelShape;
  55245. })(BABYLON || (BABYLON = {}));
  55246. var BABYLON;
  55247. (function (BABYLON) {
  55248. /**
  55249. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  55250. */
  55251. var SolidParticleSystem = (function () {
  55252. /**
  55253. * Creates a SPS (Solid Particle System) object.
  55254. * `name` (String) is the SPS name, this will be the underlying mesh name.
  55255. * `scene` (Scene) is the scene in which the SPS is added.
  55256. * `updatable` (default true) : if the SPS must be updatable or immutable.
  55257. * `isPickable` (default false) : if the solid particles must be pickable.
  55258. */
  55259. function SolidParticleSystem(name, scene, options) {
  55260. // public members
  55261. /**
  55262. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  55263. * Example : var p = SPS.particles[i];
  55264. */
  55265. this.particles = new Array();
  55266. /**
  55267. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  55268. */
  55269. this.nbParticles = 0;
  55270. /**
  55271. * If the particles must ever face the camera (default false). Useful for planar particles.
  55272. */
  55273. this.billboard = false;
  55274. /**
  55275. * This a counter ofr your own usage. It's not set by any SPS functions.
  55276. */
  55277. this.counter = 0;
  55278. /**
  55279. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  55280. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  55281. */
  55282. this.vars = {};
  55283. this._positions = new Array();
  55284. this._indices = new Array();
  55285. this._normals = new Array();
  55286. this._colors = new Array();
  55287. this._uvs = new Array();
  55288. this._index = 0; // indices index
  55289. this._updatable = true;
  55290. this._pickable = false;
  55291. this._isVisibilityBoxLocked = false;
  55292. this._alwaysVisible = false;
  55293. this._shapeCounter = 0;
  55294. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  55295. this._color = new BABYLON.Color4(0, 0, 0, 0);
  55296. this._computeParticleColor = true;
  55297. this._computeParticleTexture = true;
  55298. this._computeParticleRotation = true;
  55299. this._computeParticleVertex = false;
  55300. this._computeBoundingBox = false;
  55301. this._cam_axisZ = BABYLON.Vector3.Zero();
  55302. this._cam_axisY = BABYLON.Vector3.Zero();
  55303. this._cam_axisX = BABYLON.Vector3.Zero();
  55304. this._axisX = BABYLON.Axis.X;
  55305. this._axisY = BABYLON.Axis.Y;
  55306. this._axisZ = BABYLON.Axis.Z;
  55307. this._fakeCamPos = BABYLON.Vector3.Zero();
  55308. this._rotMatrix = new BABYLON.Matrix();
  55309. this._invertMatrix = new BABYLON.Matrix();
  55310. this._rotated = BABYLON.Vector3.Zero();
  55311. this._quaternion = new BABYLON.Quaternion();
  55312. this._vertex = BABYLON.Vector3.Zero();
  55313. this._normal = BABYLON.Vector3.Zero();
  55314. this._yaw = 0.0;
  55315. this._pitch = 0.0;
  55316. this._roll = 0.0;
  55317. this._halfroll = 0.0;
  55318. this._halfpitch = 0.0;
  55319. this._halfyaw = 0.0;
  55320. this._sinRoll = 0.0;
  55321. this._cosRoll = 0.0;
  55322. this._sinPitch = 0.0;
  55323. this._cosPitch = 0.0;
  55324. this._sinYaw = 0.0;
  55325. this._cosYaw = 0.0;
  55326. this._w = 0.0;
  55327. this._minimum = BABYLON.Tmp.Vector3[0];
  55328. this._maximum = BABYLON.Tmp.Vector3[1];
  55329. this.name = name;
  55330. this._scene = scene;
  55331. this._camera = scene.activeCamera;
  55332. this._pickable = options ? options.isPickable : false;
  55333. if (options && options.updatable) {
  55334. this._updatable = options.updatable;
  55335. }
  55336. else {
  55337. this._updatable = true;
  55338. }
  55339. if (this._pickable) {
  55340. this.pickedParticles = [];
  55341. }
  55342. }
  55343. /**
  55344. * Builds the SPS underlying mesh. Returns a standard Mesh.
  55345. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  55346. */
  55347. SolidParticleSystem.prototype.buildMesh = function () {
  55348. if (this.nbParticles === 0) {
  55349. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  55350. this.addShape(triangle, 1);
  55351. triangle.dispose();
  55352. }
  55353. this._positions32 = new Float32Array(this._positions);
  55354. this._uvs32 = new Float32Array(this._uvs);
  55355. this._colors32 = new Float32Array(this._colors);
  55356. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  55357. this._normals32 = new Float32Array(this._normals);
  55358. this._fixedNormal32 = new Float32Array(this._normals);
  55359. var vertexData = new BABYLON.VertexData();
  55360. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  55361. vertexData.indices = this._indices;
  55362. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  55363. if (this._uvs32) {
  55364. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  55365. ;
  55366. }
  55367. if (this._colors32) {
  55368. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  55369. }
  55370. var mesh = new BABYLON.Mesh(this.name, this._scene);
  55371. vertexData.applyToMesh(mesh, this._updatable);
  55372. this.mesh = mesh;
  55373. this.mesh.isPickable = this._pickable;
  55374. // free memory
  55375. this._positions = null;
  55376. this._normals = null;
  55377. this._uvs = null;
  55378. this._colors = null;
  55379. if (!this._updatable) {
  55380. this.particles.length = 0;
  55381. }
  55382. return mesh;
  55383. };
  55384. /**
  55385. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  55386. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  55387. * Thus the particles generated from `digest()` have their property `position` set yet.
  55388. * `mesh` ( Mesh ) is the mesh to be digested
  55389. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  55390. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55391. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55392. */
  55393. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55394. var size = (options && options.facetNb) || 1;
  55395. var number = (options && options.number);
  55396. var delta = (options && options.delta) || 0;
  55397. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55398. var meshInd = mesh.getIndices();
  55399. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55400. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55401. var f = 0; // facet counter
  55402. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55403. // compute size from number
  55404. if (number) {
  55405. number = (number > totalFacets) ? totalFacets : number;
  55406. size = Math.round(totalFacets / number);
  55407. delta = 0;
  55408. }
  55409. else {
  55410. size = (size > totalFacets) ? totalFacets : size;
  55411. }
  55412. var facetPos = []; // submesh positions
  55413. var facetInd = []; // submesh indices
  55414. var facetUV = []; // submesh UV
  55415. var facetCol = []; // submesh colors
  55416. var barycenter = BABYLON.Tmp.Vector3[0];
  55417. var rand;
  55418. var sizeO = size;
  55419. while (f < totalFacets) {
  55420. size = sizeO + Math.floor((1 + delta) * Math.random());
  55421. if (f > totalFacets - size) {
  55422. size = totalFacets - f;
  55423. }
  55424. // reset temp arrays
  55425. facetPos.length = 0;
  55426. facetInd.length = 0;
  55427. facetUV.length = 0;
  55428. facetCol.length = 0;
  55429. // iterate over "size" facets
  55430. var fi = 0;
  55431. for (var j = f * 3; j < (f + size) * 3; j++) {
  55432. facetInd.push(fi);
  55433. var i = meshInd[j];
  55434. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55435. if (meshUV) {
  55436. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55437. }
  55438. if (meshCol) {
  55439. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55440. }
  55441. fi++;
  55442. }
  55443. // create a model shape for each single particle
  55444. var idx = this.nbParticles;
  55445. var shape = this._posToShape(facetPos);
  55446. var shapeUV = this._uvsToShapeUV(facetUV);
  55447. // compute the barycenter of the shape
  55448. var v;
  55449. for (v = 0; v < shape.length; v++) {
  55450. barycenter.addInPlace(shape[v]);
  55451. }
  55452. barycenter.scaleInPlace(1 / shape.length);
  55453. // shift the shape from its barycenter to the origin
  55454. for (v = 0; v < shape.length; v++) {
  55455. shape[v].subtractInPlace(barycenter);
  55456. }
  55457. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  55458. // add the particle in the SPS
  55459. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  55460. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  55461. // initialize the particle position
  55462. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55463. this._index += shape.length;
  55464. idx++;
  55465. this.nbParticles++;
  55466. this._shapeCounter++;
  55467. f += size;
  55468. }
  55469. return this;
  55470. };
  55471. //reset copy
  55472. SolidParticleSystem.prototype._resetCopy = function () {
  55473. this._copy.position.x = 0;
  55474. this._copy.position.y = 0;
  55475. this._copy.position.z = 0;
  55476. this._copy.rotation.x = 0;
  55477. this._copy.rotation.y = 0;
  55478. this._copy.rotation.z = 0;
  55479. this._copy.rotationQuaternion = null;
  55480. this._copy.scaling.x = 1;
  55481. this._copy.scaling.y = 1;
  55482. this._copy.scaling.z = 1;
  55483. this._copy.uvs.x = 0;
  55484. this._copy.uvs.y = 0;
  55485. this._copy.uvs.z = 1;
  55486. this._copy.uvs.w = 1;
  55487. this._copy.color = null;
  55488. };
  55489. // _meshBuilder : inserts the shape model in the global SPS mesh
  55490. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  55491. var i;
  55492. var u = 0;
  55493. var c = 0;
  55494. this._resetCopy();
  55495. if (options && options.positionFunction) {
  55496. options.positionFunction(this._copy, idx, idxInShape);
  55497. }
  55498. if (this._copy.rotationQuaternion) {
  55499. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55500. }
  55501. else {
  55502. this._yaw = this._copy.rotation.y;
  55503. this._pitch = this._copy.rotation.x;
  55504. this._roll = this._copy.rotation.z;
  55505. this._quaternionRotationYPR();
  55506. }
  55507. this._quaternionToRotationMatrix();
  55508. for (i = 0; i < shape.length; i++) {
  55509. this._vertex.x = shape[i].x;
  55510. this._vertex.y = shape[i].y;
  55511. this._vertex.z = shape[i].z;
  55512. if (options && options.vertexFunction) {
  55513. options.vertexFunction(this._copy, this._vertex, i);
  55514. }
  55515. this._vertex.x *= this._copy.scaling.x;
  55516. this._vertex.y *= this._copy.scaling.y;
  55517. this._vertex.z *= this._copy.scaling.z;
  55518. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55519. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55520. if (meshUV) {
  55521. 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);
  55522. u += 2;
  55523. }
  55524. if (this._copy.color) {
  55525. this._color = this._copy.color;
  55526. }
  55527. else if (meshCol && meshCol[c] !== undefined) {
  55528. this._color.r = meshCol[c];
  55529. this._color.g = meshCol[c + 1];
  55530. this._color.b = meshCol[c + 2];
  55531. this._color.a = meshCol[c + 3];
  55532. }
  55533. else {
  55534. this._color.r = 1;
  55535. this._color.g = 1;
  55536. this._color.b = 1;
  55537. this._color.a = 1;
  55538. }
  55539. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55540. c += 4;
  55541. }
  55542. for (i = 0; i < meshInd.length; i++) {
  55543. indices.push(p + meshInd[i]);
  55544. }
  55545. if (this._pickable) {
  55546. var nbfaces = meshInd.length / 3;
  55547. for (i = 0; i < nbfaces; i++) {
  55548. this.pickedParticles.push({ idx: idx, faceId: i });
  55549. }
  55550. }
  55551. };
  55552. // returns a shape array from positions array
  55553. SolidParticleSystem.prototype._posToShape = function (positions) {
  55554. var shape = [];
  55555. for (var i = 0; i < positions.length; i += 3) {
  55556. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55557. }
  55558. return shape;
  55559. };
  55560. // returns a shapeUV array from a Vector4 uvs
  55561. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55562. var shapeUV = [];
  55563. if (uvs) {
  55564. for (var i = 0; i < uvs.length; i++)
  55565. shapeUV.push(uvs[i]);
  55566. }
  55567. return shapeUV;
  55568. };
  55569. // adds a new particle object in the particles array
  55570. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  55571. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  55572. };
  55573. /**
  55574. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55575. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55576. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  55577. * `nb` (positive integer) the number of particles to be created from this model
  55578. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  55579. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  55580. */
  55581. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55582. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55583. var meshInd = mesh.getIndices();
  55584. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55585. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55586. var shape = this._posToShape(meshPos);
  55587. var shapeUV = this._uvsToShapeUV(meshUV);
  55588. var posfunc = options ? options.positionFunction : null;
  55589. var vtxfunc = options ? options.vertexFunction : null;
  55590. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  55591. // particles
  55592. var idx = this.nbParticles;
  55593. for (var i = 0; i < nb; i++) {
  55594. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  55595. if (this._updatable) {
  55596. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  55597. }
  55598. this._index += shape.length;
  55599. idx++;
  55600. }
  55601. this.nbParticles += nb;
  55602. this._shapeCounter++;
  55603. return this._shapeCounter - 1;
  55604. };
  55605. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55606. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55607. this._resetCopy();
  55608. if (particle._model._positionFunction) {
  55609. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55610. }
  55611. if (this._copy.rotationQuaternion) {
  55612. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55613. }
  55614. else {
  55615. this._yaw = this._copy.rotation.y;
  55616. this._pitch = this._copy.rotation.x;
  55617. this._roll = this._copy.rotation.z;
  55618. this._quaternionRotationYPR();
  55619. }
  55620. this._quaternionToRotationMatrix();
  55621. this._shape = particle._model._shape;
  55622. for (var pt = 0; pt < this._shape.length; pt++) {
  55623. this._vertex.x = this._shape[pt].x;
  55624. this._vertex.y = this._shape[pt].y;
  55625. this._vertex.z = this._shape[pt].z;
  55626. if (particle._model._vertexFunction) {
  55627. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55628. }
  55629. this._vertex.x *= this._copy.scaling.x;
  55630. this._vertex.y *= this._copy.scaling.y;
  55631. this._vertex.z *= this._copy.scaling.z;
  55632. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55633. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55634. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55635. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55636. }
  55637. particle.position.x = 0;
  55638. particle.position.y = 0;
  55639. particle.position.z = 0;
  55640. particle.rotation.x = 0;
  55641. particle.rotation.y = 0;
  55642. particle.rotation.z = 0;
  55643. particle.rotationQuaternion = null;
  55644. particle.scaling.x = 1;
  55645. particle.scaling.y = 1;
  55646. particle.scaling.z = 1;
  55647. };
  55648. /**
  55649. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55650. */
  55651. SolidParticleSystem.prototype.rebuildMesh = function () {
  55652. for (var p = 0; p < this.particles.length; p++) {
  55653. this._rebuildParticle(this.particles[p]);
  55654. }
  55655. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55656. };
  55657. /**
  55658. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55659. * This method calls `updateParticle()` for each particle of the SPS.
  55660. * For an animated SPS, it is usually called within the render loop.
  55661. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55662. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55663. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55664. */
  55665. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55666. if (start === void 0) { start = 0; }
  55667. if (end === void 0) { end = this.nbParticles - 1; }
  55668. if (update === void 0) { update = true; }
  55669. if (!this._updatable) {
  55670. return;
  55671. }
  55672. // custom beforeUpdate
  55673. this.beforeUpdateParticles(start, end, update);
  55674. this._cam_axisX.x = 1;
  55675. this._cam_axisX.y = 0;
  55676. this._cam_axisX.z = 0;
  55677. this._cam_axisY.x = 0;
  55678. this._cam_axisY.y = 1;
  55679. this._cam_axisY.z = 0;
  55680. this._cam_axisZ.x = 0;
  55681. this._cam_axisZ.y = 0;
  55682. this._cam_axisZ.z = 1;
  55683. // if the particles will always face the camera
  55684. if (this.billboard) {
  55685. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  55686. this._yaw = this.mesh.rotation.y;
  55687. this._pitch = this.mesh.rotation.x;
  55688. this._roll = this.mesh.rotation.z;
  55689. this._quaternionRotationYPR();
  55690. this._quaternionToRotationMatrix();
  55691. this._rotMatrix.invertToRef(this._invertMatrix);
  55692. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  55693. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  55694. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  55695. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  55696. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  55697. this._cam_axisY.normalize();
  55698. this._cam_axisX.normalize();
  55699. this._cam_axisZ.normalize();
  55700. }
  55701. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55702. var idx = 0;
  55703. var index = 0;
  55704. var colidx = 0;
  55705. var colorIndex = 0;
  55706. var uvidx = 0;
  55707. var uvIndex = 0;
  55708. var pt = 0;
  55709. if (this._computeBoundingBox) {
  55710. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55711. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55712. }
  55713. // particle loop
  55714. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  55715. for (var p = start; p <= end; p++) {
  55716. this._particle = this.particles[p];
  55717. this._shape = this._particle._model._shape;
  55718. this._shapeUV = this._particle._model._shapeUV;
  55719. // call to custom user function to update the particle properties
  55720. this.updateParticle(this._particle);
  55721. if (this._particle.isVisible) {
  55722. // particle rotation matrix
  55723. if (this.billboard) {
  55724. this._particle.rotation.x = 0.0;
  55725. this._particle.rotation.y = 0.0;
  55726. }
  55727. if (this._computeParticleRotation) {
  55728. if (this._particle.rotationQuaternion) {
  55729. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55730. }
  55731. else {
  55732. this._yaw = this._particle.rotation.y;
  55733. this._pitch = this._particle.rotation.x;
  55734. this._roll = this._particle.rotation.z;
  55735. this._quaternionRotationYPR();
  55736. }
  55737. this._quaternionToRotationMatrix();
  55738. }
  55739. // particle vertex loop
  55740. for (pt = 0; pt < this._shape.length; pt++) {
  55741. idx = index + pt * 3;
  55742. colidx = colorIndex + pt * 4;
  55743. uvidx = uvIndex + pt * 2;
  55744. this._vertex.x = this._shape[pt].x;
  55745. this._vertex.y = this._shape[pt].y;
  55746. this._vertex.z = this._shape[pt].z;
  55747. if (this._computeParticleVertex) {
  55748. this.updateParticleVertex(this._particle, this._vertex, pt);
  55749. }
  55750. // positions
  55751. this._vertex.x *= this._particle.scaling.x;
  55752. this._vertex.y *= this._particle.scaling.y;
  55753. this._vertex.z *= this._particle.scaling.z;
  55754. 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];
  55755. 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;
  55756. 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;
  55757. 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;
  55758. 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;
  55759. 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;
  55760. 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;
  55761. if (this._computeBoundingBox) {
  55762. if (this._positions32[idx] < this._minimum.x) {
  55763. this._minimum.x = this._positions32[idx];
  55764. }
  55765. if (this._positions32[idx] > this._maximum.x) {
  55766. this._maximum.x = this._positions32[idx];
  55767. }
  55768. if (this._positions32[idx + 1] < this._minimum.y) {
  55769. this._minimum.y = this._positions32[idx + 1];
  55770. }
  55771. if (this._positions32[idx + 1] > this._maximum.y) {
  55772. this._maximum.y = this._positions32[idx + 1];
  55773. }
  55774. if (this._positions32[idx + 2] < this._minimum.z) {
  55775. this._minimum.z = this._positions32[idx + 2];
  55776. }
  55777. if (this._positions32[idx + 2] > this._maximum.z) {
  55778. this._maximum.z = this._positions32[idx + 2];
  55779. }
  55780. }
  55781. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  55782. if (!this._computeParticleVertex && !this.billboard) {
  55783. this._normal.x = this._fixedNormal32[idx];
  55784. this._normal.y = this._fixedNormal32[idx + 1];
  55785. this._normal.z = this._fixedNormal32[idx + 2];
  55786. 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];
  55787. 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;
  55788. 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;
  55789. 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;
  55790. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55791. 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;
  55792. 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;
  55793. }
  55794. if (this._computeParticleColor) {
  55795. this._colors32[colidx] = this._particle.color.r;
  55796. this._colors32[colidx + 1] = this._particle.color.g;
  55797. this._colors32[colidx + 2] = this._particle.color.b;
  55798. this._colors32[colidx + 3] = this._particle.color.a;
  55799. }
  55800. if (this._computeParticleTexture) {
  55801. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55802. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55803. }
  55804. }
  55805. }
  55806. else {
  55807. for (pt = 0; pt < this._shape.length; pt++) {
  55808. idx = index + pt * 3;
  55809. colidx = colorIndex + pt * 4;
  55810. uvidx = uvIndex + pt * 2;
  55811. this._positions32[idx] = this._camera.position.x;
  55812. this._positions32[idx + 1] = this._camera.position.y;
  55813. this._positions32[idx + 2] = this._camera.position.z;
  55814. this._normals32[idx] = 0.0;
  55815. this._normals32[idx + 1] = 0.0;
  55816. this._normals32[idx + 2] = 0.0;
  55817. if (this._computeParticleColor) {
  55818. this._colors32[colidx] = this._particle.color.r;
  55819. this._colors32[colidx + 1] = this._particle.color.g;
  55820. this._colors32[colidx + 2] = this._particle.color.b;
  55821. this._colors32[colidx + 3] = this._particle.color.a;
  55822. }
  55823. if (this._computeParticleTexture) {
  55824. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55825. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55826. }
  55827. }
  55828. }
  55829. // increment indexes for the next particle
  55830. index = idx + 3;
  55831. colorIndex = colidx + 4;
  55832. uvIndex = uvidx + 2;
  55833. }
  55834. // if the VBO must be updated
  55835. if (update) {
  55836. if (this._computeParticleColor) {
  55837. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55838. }
  55839. if (this._computeParticleTexture) {
  55840. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55841. }
  55842. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55843. if (!this.mesh.areNormalsFrozen) {
  55844. if (this._computeParticleVertex || this.billboard) {
  55845. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55846. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  55847. for (var i = 0; i < this._normals32.length; i++) {
  55848. this._fixedNormal32[i] = this._normals32[i];
  55849. }
  55850. }
  55851. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55852. }
  55853. }
  55854. if (this._computeBoundingBox) {
  55855. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55856. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55857. }
  55858. this.afterUpdateParticles(start, end, update);
  55859. };
  55860. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55861. this._halfroll = this._roll * 0.5;
  55862. this._halfpitch = this._pitch * 0.5;
  55863. this._halfyaw = this._yaw * 0.5;
  55864. this._sinRoll = Math.sin(this._halfroll);
  55865. this._cosRoll = Math.cos(this._halfroll);
  55866. this._sinPitch = Math.sin(this._halfpitch);
  55867. this._cosPitch = Math.cos(this._halfpitch);
  55868. this._sinYaw = Math.sin(this._halfyaw);
  55869. this._cosYaw = Math.cos(this._halfyaw);
  55870. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  55871. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  55872. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  55873. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  55874. };
  55875. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55876. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55877. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55878. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55879. this._rotMatrix.m[3] = 0;
  55880. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55881. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55882. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55883. this._rotMatrix.m[7] = 0;
  55884. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55885. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55886. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55887. this._rotMatrix.m[11] = 0;
  55888. this._rotMatrix.m[12] = 0;
  55889. this._rotMatrix.m[13] = 0;
  55890. this._rotMatrix.m[14] = 0;
  55891. this._rotMatrix.m[15] = 1.0;
  55892. };
  55893. /**
  55894. * Disposes the SPS
  55895. */
  55896. SolidParticleSystem.prototype.dispose = function () {
  55897. this.mesh.dispose();
  55898. this.vars = null;
  55899. // drop references to internal big arrays for the GC
  55900. this._positions = null;
  55901. this._indices = null;
  55902. this._normals = null;
  55903. this._uvs = null;
  55904. this._colors = null;
  55905. this._positions32 = null;
  55906. this._normals32 = null;
  55907. this._fixedNormal32 = null;
  55908. this._uvs32 = null;
  55909. this._colors32 = null;
  55910. this.pickedParticles = null;
  55911. };
  55912. /**
  55913. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55915. */
  55916. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55917. if (!this._isVisibilityBoxLocked) {
  55918. this.mesh.refreshBoundingInfo();
  55919. }
  55920. };
  55921. /**
  55922. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55923. * @param size the size (float) of the visibility box
  55924. * note : this doesn't lock the SPS mesh bounding box.
  55925. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55926. */
  55927. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55928. var vis = size / 2;
  55929. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55930. };
  55931. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55932. // getter and setter
  55933. get: function () {
  55934. return this._alwaysVisible;
  55935. },
  55936. /**
  55937. * Sets the SPS as always visible or not
  55938. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55939. */
  55940. set: function (val) {
  55941. this._alwaysVisible = val;
  55942. this.mesh.alwaysSelectAsActiveMesh = val;
  55943. },
  55944. enumerable: true,
  55945. configurable: true
  55946. });
  55947. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55948. get: function () {
  55949. return this._isVisibilityBoxLocked;
  55950. },
  55951. /**
  55952. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55953. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55954. */
  55955. set: function (val) {
  55956. this._isVisibilityBoxLocked = val;
  55957. this.mesh.getBoundingInfo().isLocked = val;
  55958. },
  55959. enumerable: true,
  55960. configurable: true
  55961. });
  55962. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55963. // getters
  55964. get: function () {
  55965. return this._computeParticleRotation;
  55966. },
  55967. // Optimizer setters
  55968. /**
  55969. * Tells to `setParticles()` to compute the particle rotations or not.
  55970. * Default value : true. The SPS is faster when it's set to false.
  55971. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55972. */
  55973. set: function (val) {
  55974. this._computeParticleRotation = val;
  55975. },
  55976. enumerable: true,
  55977. configurable: true
  55978. });
  55979. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55980. get: function () {
  55981. return this._computeParticleColor;
  55982. },
  55983. /**
  55984. * Tells to `setParticles()` to compute the particle colors or not.
  55985. * Default value : true. The SPS is faster when it's set to false.
  55986. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55987. */
  55988. set: function (val) {
  55989. this._computeParticleColor = val;
  55990. },
  55991. enumerable: true,
  55992. configurable: true
  55993. });
  55994. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55995. get: function () {
  55996. return this._computeParticleTexture;
  55997. },
  55998. /**
  55999. * Tells to `setParticles()` to compute the particle textures or not.
  56000. * Default value : true. The SPS is faster when it's set to false.
  56001. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  56002. */
  56003. set: function (val) {
  56004. this._computeParticleTexture = val;
  56005. },
  56006. enumerable: true,
  56007. configurable: true
  56008. });
  56009. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  56010. get: function () {
  56011. return this._computeParticleVertex;
  56012. },
  56013. /**
  56014. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  56015. * Default value : false. The SPS is faster when it's set to false.
  56016. * Note : the particle custom vertex positions aren't stored values.
  56017. */
  56018. set: function (val) {
  56019. this._computeParticleVertex = val;
  56020. },
  56021. enumerable: true,
  56022. configurable: true
  56023. });
  56024. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  56025. get: function () {
  56026. return this._computeBoundingBox;
  56027. },
  56028. /**
  56029. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  56030. */
  56031. set: function (val) {
  56032. this._computeBoundingBox = val;
  56033. },
  56034. enumerable: true,
  56035. configurable: true
  56036. });
  56037. // =======================================================================
  56038. // Particle behavior logic
  56039. // these following methods may be overwritten by the user to fit his needs
  56040. /**
  56041. * This function does nothing. It may be overwritten to set all the particle first values.
  56042. * The SPS doesn't call this function, you may have to call it by your own.
  56043. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56044. */
  56045. SolidParticleSystem.prototype.initParticles = function () {
  56046. };
  56047. /**
  56048. * This function does nothing. It may be overwritten to recycle a particle.
  56049. * The SPS doesn't call this function, you may have to call it by your own.
  56050. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56051. */
  56052. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  56053. return particle;
  56054. };
  56055. /**
  56056. * Updates a particle : this function should be overwritten by the user.
  56057. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  56058. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  56059. * ex : just set a particle position or velocity and recycle conditions
  56060. */
  56061. SolidParticleSystem.prototype.updateParticle = function (particle) {
  56062. return particle;
  56063. };
  56064. /**
  56065. * Updates a vertex of a particle : it can be overwritten by the user.
  56066. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  56067. * @param particle the current particle
  56068. * @param vertex the current index of the current particle
  56069. * @param pt the index of the current vertex in the particle shape
  56070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  56071. * ex : just set a vertex particle position
  56072. */
  56073. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  56074. return vertex;
  56075. };
  56076. /**
  56077. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  56078. * This does nothing and may be overwritten by the user.
  56079. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56080. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56081. * @param update the boolean update value actually passed to setParticles()
  56082. */
  56083. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56084. };
  56085. /**
  56086. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56087. * This will be passed three parameters.
  56088. * This does nothing and may be overwritten by the user.
  56089. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56090. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56091. * @param update the boolean update value actually passed to setParticles()
  56092. */
  56093. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56094. };
  56095. return SolidParticleSystem;
  56096. })();
  56097. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56098. })(BABYLON || (BABYLON = {}));
  56099. var BABYLON;
  56100. (function (BABYLON) {
  56101. var Internals;
  56102. (function (Internals) {
  56103. var FileFaceOrientation = (function () {
  56104. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  56105. this.name = name;
  56106. this.worldAxisForNormal = worldAxisForNormal;
  56107. this.worldAxisForFileX = worldAxisForFileX;
  56108. this.worldAxisForFileY = worldAxisForFileY;
  56109. }
  56110. return FileFaceOrientation;
  56111. })();
  56112. ;
  56113. /**
  56114. * Helper class dealing with the extraction of spherical polynomial dataArray
  56115. * from a cube map.
  56116. */
  56117. var CubeMapToSphericalPolynomialTools = (function () {
  56118. function CubeMapToSphericalPolynomialTools() {
  56119. }
  56120. /**
  56121. * Converts a cubemap to the according Spherical Polynomial data.
  56122. * This extracts the first 3 orders only as they are the only one used in the lighting.
  56123. *
  56124. * @param cubeInfo The Cube map to extract the information from.
  56125. * @return The Spherical Polynomial data.
  56126. */
  56127. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  56128. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  56129. var totalSolidAngle = 0.0;
  56130. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  56131. var du = 2.0 / cubeInfo.size;
  56132. var dv = du;
  56133. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  56134. var minUV = du * 0.5 - 1.0;
  56135. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56136. var fileFace = this.FileFaces[faceIndex];
  56137. var dataArray = cubeInfo[fileFace.name];
  56138. var v = minUV;
  56139. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  56140. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  56141. // Because SP is still linear, so summation is fine in that basis.
  56142. for (var y = 0; y < cubeInfo.size; y++) {
  56143. var u = minUV;
  56144. for (var x = 0; x < cubeInfo.size; x++) {
  56145. // World direction (not normalised)
  56146. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  56147. worldDirection.normalize();
  56148. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  56149. if (1) {
  56150. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  56151. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  56152. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  56153. var color = new BABYLON.Color3(r, g, b);
  56154. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56155. }
  56156. else {
  56157. if (faceIndex == 0) {
  56158. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56159. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56160. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56161. }
  56162. else if (faceIndex == 1) {
  56163. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56164. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56165. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56166. }
  56167. else if (faceIndex == 2) {
  56168. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56169. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56170. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56171. }
  56172. else if (faceIndex == 3) {
  56173. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56174. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56175. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  56176. }
  56177. else if (faceIndex == 4) {
  56178. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  56179. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  56180. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56181. }
  56182. else if (faceIndex == 5) {
  56183. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  56184. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  56185. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  56186. }
  56187. 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]);
  56188. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  56189. }
  56190. totalSolidAngle += deltaSolidAngle;
  56191. u += du;
  56192. }
  56193. v += dv;
  56194. }
  56195. }
  56196. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  56197. var correction = correctSolidAngle / totalSolidAngle;
  56198. sphericalHarmonics.scale(correction);
  56199. // Additionally scale by pi -- audit needed
  56200. sphericalHarmonics.scale(1.0 / Math.PI);
  56201. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  56202. };
  56203. CubeMapToSphericalPolynomialTools.FileFaces = [
  56204. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  56205. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  56206. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  56207. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  56208. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  56209. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  56210. ];
  56211. return CubeMapToSphericalPolynomialTools;
  56212. })();
  56213. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  56214. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56215. })(BABYLON || (BABYLON = {}));
  56216. var BABYLON;
  56217. (function (BABYLON) {
  56218. var Internals;
  56219. (function (Internals) {
  56220. /**
  56221. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  56222. */
  56223. var PanoramaToCubeMapTools = (function () {
  56224. function PanoramaToCubeMapTools() {
  56225. }
  56226. /**
  56227. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  56228. *
  56229. * @param float32Array The source data.
  56230. * @param inputWidth The width of the input panorama.
  56231. * @param inputhHeight The height of the input panorama.
  56232. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  56233. * @return The cubemap data
  56234. */
  56235. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  56236. if (!float32Array) {
  56237. throw "ConvertPanoramaToCubemap: input cannot be null";
  56238. }
  56239. if (float32Array.length != inputWidth * inputHeight * 3) {
  56240. throw "ConvertPanoramaToCubemap: input size is wrong";
  56241. }
  56242. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  56243. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  56244. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  56245. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  56246. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  56247. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  56248. return {
  56249. front: textureFront,
  56250. back: textureBack,
  56251. left: textureLeft,
  56252. right: textureRight,
  56253. up: textureUp,
  56254. down: textureDown,
  56255. size: size
  56256. };
  56257. };
  56258. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  56259. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  56260. var textureArray = new Float32Array(buffer);
  56261. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  56262. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  56263. var dy = 1 / texSize;
  56264. var fy = 0;
  56265. for (var y = 0; y < texSize; y++) {
  56266. var xv1 = faceData[0];
  56267. var xv2 = faceData[2];
  56268. for (var x = 0; x < texSize; x++) {
  56269. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  56270. v.normalize();
  56271. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  56272. // 3 channels per pixels
  56273. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  56274. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  56275. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  56276. xv1 = xv1.add(rotDX1);
  56277. xv2 = xv2.add(rotDX2);
  56278. }
  56279. fy += dy;
  56280. }
  56281. return textureArray;
  56282. };
  56283. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  56284. var theta = Math.atan2(vDir.z, vDir.x);
  56285. var phi = Math.acos(vDir.y);
  56286. while (theta < -Math.PI)
  56287. theta += 2 * Math.PI;
  56288. while (theta > Math.PI)
  56289. theta -= 2 * Math.PI;
  56290. var dx = theta / Math.PI;
  56291. var dy = phi / Math.PI;
  56292. // recenter.
  56293. dx = dx * 0.5 + 0.5;
  56294. var px = Math.round(dx * inputWidth);
  56295. if (px < 0)
  56296. px = 0;
  56297. else if (px >= inputWidth)
  56298. px = inputWidth - 1;
  56299. var py = Math.round(dy * inputHeight);
  56300. if (py < 0)
  56301. py = 0;
  56302. else if (py >= inputHeight)
  56303. py = inputHeight - 1;
  56304. var inputY = (inputHeight - py - 1);
  56305. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  56306. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  56307. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  56308. return {
  56309. r: r,
  56310. g: g,
  56311. b: b
  56312. };
  56313. };
  56314. PanoramaToCubeMapTools.FACE_FRONT = [
  56315. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56316. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56317. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56318. new BABYLON.Vector3(1.0, 1.0, -1.0)
  56319. ];
  56320. PanoramaToCubeMapTools.FACE_BACK = [
  56321. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56322. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56323. new BABYLON.Vector3(1.0, 1.0, 1.0),
  56324. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  56325. ];
  56326. PanoramaToCubeMapTools.FACE_RIGHT = [
  56327. new BABYLON.Vector3(1.0, -1.0, -1.0),
  56328. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56329. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56330. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56331. ];
  56332. PanoramaToCubeMapTools.FACE_LEFT = [
  56333. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56334. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56335. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56336. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  56337. ];
  56338. PanoramaToCubeMapTools.FACE_DOWN = [
  56339. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  56340. new BABYLON.Vector3(1.0, 1.0, -1.0),
  56341. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  56342. new BABYLON.Vector3(1.0, 1.0, 1.0)
  56343. ];
  56344. PanoramaToCubeMapTools.FACE_UP = [
  56345. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  56346. new BABYLON.Vector3(1.0, -1.0, 1.0),
  56347. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  56348. new BABYLON.Vector3(1.0, -1.0, -1.0)
  56349. ];
  56350. return PanoramaToCubeMapTools;
  56351. })();
  56352. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  56353. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56354. })(BABYLON || (BABYLON = {}));
  56355. var BABYLON;
  56356. (function (BABYLON) {
  56357. var Internals;
  56358. (function (Internals) {
  56359. ;
  56360. /**
  56361. * This groups tools to convert HDR texture to native colors array.
  56362. */
  56363. var HDRTools = (function () {
  56364. function HDRTools() {
  56365. }
  56366. HDRTools.Ldexp = function (mantissa, exponent) {
  56367. if (exponent > 1023) {
  56368. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  56369. }
  56370. if (exponent < -1074) {
  56371. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  56372. }
  56373. return mantissa * Math.pow(2, exponent);
  56374. };
  56375. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  56376. if (exponent > 0) {
  56377. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  56378. float32array[index + 0] = red * exponent;
  56379. float32array[index + 1] = green * exponent;
  56380. float32array[index + 2] = blue * exponent;
  56381. }
  56382. else {
  56383. float32array[index + 0] = 0;
  56384. float32array[index + 1] = 0;
  56385. float32array[index + 2] = 0;
  56386. }
  56387. };
  56388. HDRTools.readStringLine = function (uint8array, startIndex) {
  56389. var line = "";
  56390. var character = "";
  56391. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  56392. character = String.fromCharCode(uint8array[i]);
  56393. if (character == "\n") {
  56394. break;
  56395. }
  56396. line += character;
  56397. }
  56398. return line;
  56399. };
  56400. /**
  56401. * Reads header information from an RGBE texture stored in a native array.
  56402. * More information on this format are available here:
  56403. * https://en.wikipedia.org/wiki/RGBE_image_format
  56404. *
  56405. * @param uint8array The binary file stored in native array.
  56406. * @return The header information.
  56407. */
  56408. HDRTools.RGBE_ReadHeader = function (uint8array) {
  56409. var height = 0;
  56410. var width = 0;
  56411. var line = this.readStringLine(uint8array, 0);
  56412. if (line[0] != '#' || line[1] != '?') {
  56413. throw "Bad HDR Format.";
  56414. }
  56415. var endOfHeader = false;
  56416. var findFormat = false;
  56417. var lineIndex = 0;
  56418. do {
  56419. lineIndex += (line.length + 1);
  56420. line = this.readStringLine(uint8array, lineIndex);
  56421. if (line == "FORMAT=32-bit_rle_rgbe") {
  56422. findFormat = true;
  56423. }
  56424. else if (line.length == 0) {
  56425. endOfHeader = true;
  56426. }
  56427. } while (!endOfHeader);
  56428. if (!findFormat) {
  56429. throw "HDR Bad header format, unsupported FORMAT";
  56430. }
  56431. lineIndex += (line.length + 1);
  56432. line = this.readStringLine(uint8array, lineIndex);
  56433. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  56434. var match = sizeRegexp.exec(line);
  56435. // TODO. Support +Y and -X if needed.
  56436. if (match.length < 3) {
  56437. throw "HDR Bad header format, no size";
  56438. }
  56439. width = parseInt(match[2]);
  56440. height = parseInt(match[1]);
  56441. if (width < 8 || width > 0x7fff) {
  56442. throw "HDR Bad header format, unsupported size";
  56443. }
  56444. lineIndex += (line.length + 1);
  56445. return {
  56446. height: height,
  56447. width: width,
  56448. dataPosition: lineIndex
  56449. };
  56450. };
  56451. /**
  56452. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  56453. * This RGBE texture needs to store the information as a panorama.
  56454. *
  56455. * More information on this format are available here:
  56456. * https://en.wikipedia.org/wiki/RGBE_image_format
  56457. *
  56458. * @param buffer The binary file stored in an array buffer.
  56459. * @param size The expected size of the extracted cubemap.
  56460. * @return The Cube Map information.
  56461. */
  56462. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  56463. var uint8array = new Uint8Array(buffer);
  56464. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  56465. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56466. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  56467. return cubeMapData;
  56468. };
  56469. /**
  56470. * Returns the pixels data extracted from an RGBE texture.
  56471. * This pixels will be stored left to right up to down in the R G B order in one array.
  56472. *
  56473. * More information on this format are available here:
  56474. * https://en.wikipedia.org/wiki/RGBE_image_format
  56475. *
  56476. * @param uint8array The binary file stored in an array buffer.
  56477. * @param hdrInfo The header information of the file.
  56478. * @return The pixels data in RGB right to left up to down order.
  56479. */
  56480. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  56481. // Keep for multi format supports.
  56482. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  56483. };
  56484. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  56485. var num_scanlines = hdrInfo.height;
  56486. var scanline_width = hdrInfo.width;
  56487. var a, b, c, d, count;
  56488. var dataIndex = hdrInfo.dataPosition;
  56489. var index = 0, endIndex = 0, i = 0;
  56490. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  56491. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  56492. // 3 channels of 4 bytes per pixel in float.
  56493. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  56494. var resultArray = new Float32Array(resultBuffer);
  56495. // read in each successive scanline
  56496. while (num_scanlines > 0) {
  56497. a = uint8array[dataIndex++];
  56498. b = uint8array[dataIndex++];
  56499. c = uint8array[dataIndex++];
  56500. d = uint8array[dataIndex++];
  56501. if (a != 2 || b != 2 || (c & 0x80)) {
  56502. // this file is not run length encoded
  56503. throw "HDR Bad header format, not RLE";
  56504. }
  56505. if (((c << 8) | d) != scanline_width) {
  56506. throw "HDR Bad header format, wrong scan line width";
  56507. }
  56508. index = 0;
  56509. // read each of the four channels for the scanline into the buffer
  56510. for (i = 0; i < 4; i++) {
  56511. endIndex = (i + 1) * scanline_width;
  56512. while (index < endIndex) {
  56513. a = uint8array[dataIndex++];
  56514. b = uint8array[dataIndex++];
  56515. if (a > 128) {
  56516. // a run of the same value
  56517. count = a - 128;
  56518. if ((count == 0) || (count > endIndex - index)) {
  56519. throw "HDR Bad Format, bad scanline data (run)";
  56520. }
  56521. while (count-- > 0) {
  56522. scanLineArray[index++] = b;
  56523. }
  56524. }
  56525. else {
  56526. // a non-run
  56527. count = a;
  56528. if ((count == 0) || (count > endIndex - index)) {
  56529. throw "HDR Bad Format, bad scanline data (non-run)";
  56530. }
  56531. scanLineArray[index++] = b;
  56532. if (--count > 0) {
  56533. for (var j = 0; j < count; j++) {
  56534. scanLineArray[index++] = uint8array[dataIndex++];
  56535. }
  56536. }
  56537. }
  56538. }
  56539. }
  56540. // now convert data from buffer into floats
  56541. for (i = 0; i < scanline_width; i++) {
  56542. a = scanLineArray[i];
  56543. b = scanLineArray[i + scanline_width];
  56544. c = scanLineArray[i + 2 * scanline_width];
  56545. d = scanLineArray[i + 3 * scanline_width];
  56546. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  56547. }
  56548. num_scanlines--;
  56549. }
  56550. return resultArray;
  56551. };
  56552. return HDRTools;
  56553. })();
  56554. Internals.HDRTools = HDRTools;
  56555. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56556. })(BABYLON || (BABYLON = {}));
  56557. //_______________________________________________________________
  56558. // Extracted from CubeMapGen:
  56559. // https://code.google.com/archive/p/cubemapgen/
  56560. //
  56561. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56562. //_______________________________________________________________
  56563. var BABYLON;
  56564. (function (BABYLON) {
  56565. var Internals;
  56566. (function (Internals) {
  56567. /**
  56568. * The bounding box information used during the conversion process.
  56569. */
  56570. var CMGBoundinBox = (function () {
  56571. function CMGBoundinBox() {
  56572. this.min = new BABYLON.Vector3(0, 0, 0);
  56573. this.max = new BABYLON.Vector3(0, 0, 0);
  56574. this.clear();
  56575. }
  56576. CMGBoundinBox.prototype.clear = function () {
  56577. this.min.x = CMGBoundinBox.MAX;
  56578. this.min.y = CMGBoundinBox.MAX;
  56579. this.min.z = CMGBoundinBox.MAX;
  56580. this.max.x = CMGBoundinBox.MIN;
  56581. this.max.y = CMGBoundinBox.MIN;
  56582. this.max.z = CMGBoundinBox.MIN;
  56583. };
  56584. CMGBoundinBox.prototype.augment = function (x, y, z) {
  56585. this.min.x = Math.min(this.min.x, x);
  56586. this.min.y = Math.min(this.min.y, y);
  56587. this.min.z = Math.min(this.min.z, z);
  56588. this.max.x = Math.max(this.max.x, x);
  56589. this.max.y = Math.max(this.max.y, y);
  56590. this.max.z = Math.max(this.max.z, z);
  56591. };
  56592. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  56593. this.min.x = Math.max(this.min.x, x);
  56594. this.min.y = Math.max(this.min.y, y);
  56595. this.min.z = Math.max(this.min.z, z);
  56596. };
  56597. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  56598. this.max.x = Math.min(this.max.x, x);
  56599. this.max.y = Math.min(this.max.y, y);
  56600. this.max.z = Math.min(this.max.z, z);
  56601. };
  56602. CMGBoundinBox.prototype.empty = function () {
  56603. if ((this.min.x > this.max.y) ||
  56604. (this.min.y > this.max.y) ||
  56605. (this.min.z > this.max.y)) {
  56606. return true;
  56607. }
  56608. else {
  56609. return false;
  56610. }
  56611. };
  56612. CMGBoundinBox.MAX = Number.MAX_VALUE;
  56613. CMGBoundinBox.MIN = Number.MIN_VALUE;
  56614. return CMGBoundinBox;
  56615. })();
  56616. /**
  56617. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  56618. * required by the glossinees of a material.
  56619. *
  56620. * This only supports the cosine drop power as well as Warp fixup generation method.
  56621. *
  56622. * This is using the process from CubeMapGen described here:
  56623. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  56624. */
  56625. var PMREMGenerator = (function () {
  56626. /**
  56627. * Constructor of the generator.
  56628. *
  56629. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  56630. * @param inputSize The size of the cubemap faces
  56631. * @param outputSize The size of the output cubemap faces
  56632. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  56633. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  56634. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  56635. * @param specularPower The max specular level of the desired cubemap
  56636. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  56637. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  56638. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  56639. */
  56640. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  56641. this.input = input;
  56642. this.inputSize = inputSize;
  56643. this.outputSize = outputSize;
  56644. this.maxNumMipLevels = maxNumMipLevels;
  56645. this.numChannels = numChannels;
  56646. this.isFloat = isFloat;
  56647. this.specularPower = specularPower;
  56648. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  56649. this.excludeBase = excludeBase;
  56650. this.fixup = fixup;
  56651. this._outputSurface = [];
  56652. this._numMipLevels = 0;
  56653. }
  56654. /**
  56655. * Launches the filter process and return the result.
  56656. *
  56657. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  56658. */
  56659. PMREMGenerator.prototype.filterCubeMap = function () {
  56660. // Init cubemap processor
  56661. this.init();
  56662. // Filters the cubemap
  56663. this.filterCubeMapMipChain();
  56664. // Returns the filtered mips.
  56665. return this._outputSurface;
  56666. };
  56667. PMREMGenerator.prototype.init = function () {
  56668. var i;
  56669. var j;
  56670. var mipLevelSize;
  56671. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  56672. if (this.maxNumMipLevels == 0) {
  56673. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  56674. }
  56675. //first miplevel size
  56676. mipLevelSize = this.outputSize;
  56677. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  56678. for (j = 0; j < this.maxNumMipLevels; j++) {
  56679. this._outputSurface.length++;
  56680. this._outputSurface[j] = [];
  56681. //Iterate over faces for output images
  56682. for (i = 0; i < 6; i++) {
  56683. this._outputSurface[j].length++;
  56684. // Initializes a new array for the output.
  56685. if (this.isFloat) {
  56686. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56687. }
  56688. else {
  56689. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  56690. }
  56691. }
  56692. //next mip level is half size
  56693. mipLevelSize >>= 1;
  56694. this._numMipLevels++;
  56695. //terminate if mip chain becomes too small
  56696. if (mipLevelSize == 0) {
  56697. this.maxNumMipLevels = j;
  56698. return;
  56699. }
  56700. }
  56701. };
  56702. //--------------------------------------------------------------------------------------
  56703. //Cube map filtering and mip chain generation.
  56704. // the cube map filtereing is specified using a number of parameters:
  56705. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  56706. // indicates the region of the hemisphere to filter over for each tap.
  56707. //
  56708. // Note that the top mip level is also a filtered version of the original input images
  56709. // as well in order to create mip chains for diffuse environment illumination.
  56710. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  56711. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  56712. //
  56713. // Then the mip angle used to genreate the next level of the mip chain from the first level
  56714. // is a_InitialMipAngle
  56715. //
  56716. // The angle for the subsequent levels of the mip chain are specified by their parents
  56717. // filtering angle and a per-level scale and bias
  56718. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  56719. //
  56720. //--------------------------------------------------------------------------------------
  56721. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  56722. // First, take count of the lighting model to modify SpecularPower
  56723. // 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;
  56724. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  56725. //Cone angle start (for generating subsequent mip levels)
  56726. var currentSpecularPower = this.specularPower;
  56727. //Build filter lookup tables based on the source miplevel size
  56728. this.precomputeFilterLookupTables(this.inputSize);
  56729. // Note that we need to filter the first level before generating mipmap
  56730. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  56731. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  56732. // TODO : Write a function to copy and scale the base mipmap in output
  56733. // I am just lazy here and just put a high specular power value, and do some if.
  56734. if (this.excludeBase && (levelIndex == 0)) {
  56735. // 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).
  56736. currentSpecularPower = 100000.0;
  56737. }
  56738. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  56739. var srcCubeImage = this.input;
  56740. var dstCubeImage = this._outputSurface[levelIndex];
  56741. var dstSize = this.outputSize >> levelIndex;
  56742. // Compute required angle.
  56743. var angle = this.getBaseFilterAngle(currentSpecularPower);
  56744. // filter cube surfaces
  56745. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  56746. // fix seams
  56747. if (this.fixup) {
  56748. this.fixupCubeEdges(dstCubeImage, dstSize);
  56749. }
  56750. // Decrease the specular power to generate the mipmap chain
  56751. // TODO : Use another method for Exclude (see first comment at start of the function
  56752. if (this.excludeBase && (levelIndex == 0)) {
  56753. currentSpecularPower = this.specularPower;
  56754. }
  56755. currentSpecularPower *= this.cosinePowerDropPerMip;
  56756. }
  56757. };
  56758. //--------------------------------------------------------------------------------------
  56759. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  56760. // It allow to optimize the texel to access base on the specular power.
  56761. //--------------------------------------------------------------------------------------
  56762. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  56763. // We want to find the alpha such that:
  56764. // cos(alpha)^cosinePower = epsilon
  56765. // That's: acos(epsilon^(1/cosinePower))
  56766. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  56767. var angle = 180.0;
  56768. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  56769. angle *= 180.0 / Math.PI; // Convert to degree
  56770. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  56771. return angle;
  56772. };
  56773. //--------------------------------------------------------------------------------------
  56774. //Builds the following lookup tables prior to filtering:
  56775. // -normalizer cube map
  56776. // -tap weight lookup table
  56777. //
  56778. //--------------------------------------------------------------------------------------
  56779. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  56780. var srcTexelAngle;
  56781. var iCubeFace;
  56782. //clear pre-existing normalizer cube map
  56783. this._normCubeMap = [];
  56784. //Normalized vectors per cubeface and per-texel solid angle
  56785. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  56786. };
  56787. //--------------------------------------------------------------------------------------
  56788. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  56789. //
  56790. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  56791. //
  56792. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  56793. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  56794. // below
  56795. //--------------------------------------------------------------------------------------
  56796. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  56797. var iCubeFace;
  56798. var u;
  56799. var v;
  56800. //iterate over cube faces
  56801. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56802. //First three channels for norm cube, and last channel for solid angle
  56803. this._normCubeMap.push(new Float32Array(size * size * 4));
  56804. //fast texture walk, build normalizer cube map
  56805. var facesData = this.input[iCubeFace];
  56806. for (v = 0; v < size; v++) {
  56807. for (u = 0; u < size; u++) {
  56808. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  56809. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  56810. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  56811. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  56812. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  56813. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  56814. }
  56815. }
  56816. }
  56817. };
  56818. //--------------------------------------------------------------------------------------
  56819. // Convert cubemap face texel coordinates and face idx to 3D vector
  56820. // note the U and V coords are integer coords and range from 0 to size-1
  56821. // this routine can be used to generate a normalizer cube map
  56822. //--------------------------------------------------------------------------------------
  56823. // SL BEGIN
  56824. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  56825. var nvcU;
  56826. var nvcV;
  56827. var tempVec;
  56828. // Change from original AMD code
  56829. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56830. // + 0.5f is for texel center addressing
  56831. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  56832. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  56833. // warp fixup
  56834. if (fixup && size > 1) {
  56835. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  56836. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  56837. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  56838. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  56839. }
  56840. // Get current vector
  56841. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  56842. // U contribution
  56843. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56844. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  56845. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  56846. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  56847. // V contribution and Sum
  56848. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56849. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  56850. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  56851. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  56852. //add face axis
  56853. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  56854. PMREMGenerator._vectorTemp.x += faceAxis[0];
  56855. PMREMGenerator._vectorTemp.y += faceAxis[1];
  56856. PMREMGenerator._vectorTemp.z += faceAxis[2];
  56857. //normalize vector
  56858. PMREMGenerator._vectorTemp.normalize();
  56859. return PMREMGenerator._vectorTemp;
  56860. };
  56861. //--------------------------------------------------------------------------------------
  56862. // Convert 3D vector to cubemap face texel coordinates and face idx
  56863. // note the U and V coords are integer coords and range from 0 to size-1
  56864. // this routine can be used to generate a normalizer cube map
  56865. //
  56866. // returns face IDX and texel coords
  56867. //--------------------------------------------------------------------------------------
  56868. // SL BEGIN
  56869. /*
  56870. Mapping Texture Coordinates to Cube Map Faces
  56871. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  56872. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  56873. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  56874. map arrangement in Pixar's RenderMan package.
  56875. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  56876. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  56877. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  56878. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  56879. the major axis direction). The target column in the table below explains how the major axis direction
  56880. maps to the 2D image of a particular cube map target.
  56881. major axis
  56882. direction target sc tc ma
  56883. ---------- --------------------------------- --- --- ---
  56884. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  56885. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  56886. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  56887. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  56888. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  56889. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  56890. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  56891. an updated (s,t) is calculated as follows
  56892. s = ( sc/|ma| + 1 ) / 2
  56893. t = ( tc/|ma| + 1 ) / 2
  56894. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  56895. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  56896. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  56897. */
  56898. // Note this method return U and V in range from 0 to size-1
  56899. // SL END
  56900. // Store the information in vector3 for convenience (faceindex, u, v)
  56901. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  56902. var maxCoord;
  56903. var faceIdx;
  56904. //absolute value 3
  56905. var absX = Math.abs(x);
  56906. var absY = Math.abs(y);
  56907. var absZ = Math.abs(z);
  56908. if (absX >= absY && absX >= absZ) {
  56909. maxCoord = absX;
  56910. if (x >= 0) {
  56911. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  56912. }
  56913. else {
  56914. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56915. }
  56916. }
  56917. else if (absY >= absX && absY >= absZ) {
  56918. maxCoord = absY;
  56919. if (y >= 0) {
  56920. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56921. }
  56922. else {
  56923. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56924. }
  56925. }
  56926. else {
  56927. maxCoord = absZ;
  56928. if (z >= 0) {
  56929. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56930. }
  56931. else {
  56932. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56933. }
  56934. }
  56935. //divide through by max coord so face vector lies on cube face
  56936. var scale = 1 / maxCoord;
  56937. x *= scale;
  56938. y *= scale;
  56939. z *= scale;
  56940. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  56941. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  56942. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  56943. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  56944. // Modify original AMD code to return value from 0 to Size - 1
  56945. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  56946. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  56947. PMREMGenerator._vectorTemp.x = faceIdx;
  56948. PMREMGenerator._vectorTemp.y = u;
  56949. PMREMGenerator._vectorTemp.z = v;
  56950. return PMREMGenerator._vectorTemp;
  56951. };
  56952. //--------------------------------------------------------------------------------------
  56953. //Original code from Ignacio CastaÒo
  56954. // This formula is from Manne ÷hrstrˆm's thesis.
  56955. // Take two coordiantes in the range [-1, 1] that define a portion of a
  56956. // cube face and return the area of the projection of that portion on the
  56957. // surface of the sphere.
  56958. //--------------------------------------------------------------------------------------
  56959. PMREMGenerator.prototype.areaElement = function (x, y) {
  56960. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  56961. };
  56962. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  56963. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  56964. // (+ 0.5f is for texel center addressing)
  56965. u = (2.0 * (u + 0.5) / size) - 1.0;
  56966. v = (2.0 * (v + 0.5) / size) - 1.0;
  56967. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  56968. var invResolution = 1.0 / size;
  56969. // U and V are the -1..1 texture coordinate on the current face.
  56970. // Get projected area for this texel
  56971. var x0 = u - invResolution;
  56972. var y0 = v - invResolution;
  56973. var x1 = u + invResolution;
  56974. var y1 = v + invResolution;
  56975. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  56976. return solidAngle;
  56977. };
  56978. //--------------------------------------------------------------------------------------
  56979. //The key to the speed of these filtering routines is to quickly define a per-face
  56980. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  56981. // Later these pixels are selectively processed based on their dot products to see if
  56982. // they reside within the filtering cone.
  56983. //
  56984. //This is done by computing the smallest per-texel angle to get a conservative estimate
  56985. // of the number of texels needed to be covered in width and height order to filter the
  56986. // region. the bounding box for the center taps face is defined first, and if the
  56987. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  56988. // defined next
  56989. //--------------------------------------------------------------------------------------
  56990. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  56991. // note that pixels within these regions may be rejected
  56992. // based on the anlge
  56993. var iCubeFace;
  56994. var u;
  56995. var v;
  56996. // bounding box per face to specify region to process
  56997. var filterExtents = [];
  56998. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  56999. filterExtents.push(new CMGBoundinBox());
  57000. }
  57001. // min angle a src texel can cover (in degrees)
  57002. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  57003. // angle about center tap to define filter cone
  57004. // filter angle is 1/2 the cone angle
  57005. var filterAngle = filterConeAngle / 2.0;
  57006. //ensure filter angle is larger than a texel
  57007. if (filterAngle < srcTexelAngle) {
  57008. filterAngle = srcTexelAngle;
  57009. }
  57010. //ensure filter cone is always smaller than the hemisphere
  57011. if (filterAngle > 90.0) {
  57012. filterAngle = 90.0;
  57013. }
  57014. // the maximum number of texels in 1D the filter cone angle will cover
  57015. // used to determine bounding box size for filter extents
  57016. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  57017. // ensure conservative region always covers at least one texel
  57018. if (filterSize < 1) {
  57019. filterSize = 1;
  57020. }
  57021. // dotProdThresh threshold based on cone angle to determine whether or not taps
  57022. // reside within the cone angle
  57023. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  57024. // process required faces
  57025. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  57026. //iterate over dst cube map face texel
  57027. for (v = 0; v < dstSize; v++) {
  57028. for (u = 0; u < dstSize; u++) {
  57029. //get center tap direction
  57030. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  57031. //clear old per-face filter extents
  57032. this.clearFilterExtents(filterExtents);
  57033. //define per-face filter extents
  57034. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  57035. //perform filtering of src faces using filter extents
  57036. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  57037. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  57038. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  57039. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  57040. }
  57041. }
  57042. }
  57043. };
  57044. //--------------------------------------------------------------------------------------
  57045. //Clear filter extents for the 6 cube map faces
  57046. //--------------------------------------------------------------------------------------
  57047. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  57048. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  57049. filterExtents[iCubeFaces].clear();
  57050. }
  57051. };
  57052. //--------------------------------------------------------------------------------------
  57053. //Define per-face bounding box filter extents
  57054. //
  57055. // These define conservative texel regions in each of the faces the filter can possibly
  57056. // process. When the pixels in the regions are actually processed, the dot product
  57057. // between the tap vector and the center tap vector is used to determine the weight of
  57058. // the tap and whether or not the tap is within the cone.
  57059. //
  57060. //--------------------------------------------------------------------------------------
  57061. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  57062. //neighboring face and bleed over amount, and width of BBOX for
  57063. // left, right, top, and bottom edges of this face
  57064. var bleedOverAmount = [0, 0, 0, 0];
  57065. var bleedOverBBoxMin = [0, 0, 0, 0];
  57066. var bleedOverBBoxMax = [0, 0, 0, 0];
  57067. var neighborFace;
  57068. var neighborEdge;
  57069. var oppositeFaceIdx;
  57070. //get face idx, and u, v info from center tap dir
  57071. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  57072. var faceIdx = result.x;
  57073. var u = result.y;
  57074. var v = result.z;
  57075. //define bbox size within face
  57076. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  57077. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  57078. filterExtents[faceIdx].clampMin(0, 0, 0);
  57079. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  57080. //u and v extent in face corresponding to center tap
  57081. var minU = filterExtents[faceIdx].min.x;
  57082. var minV = filterExtents[faceIdx].min.y;
  57083. var maxU = filterExtents[faceIdx].max.x;
  57084. var maxV = filterExtents[faceIdx].max.y;
  57085. //bleed over amounts for face across u=0 edge (left)
  57086. bleedOverAmount[0] = (bboxSize - u);
  57087. bleedOverBBoxMin[0] = minV;
  57088. bleedOverBBoxMax[0] = maxV;
  57089. //bleed over amounts for face across u=1 edge (right)
  57090. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  57091. bleedOverBBoxMin[1] = minV;
  57092. bleedOverBBoxMax[1] = maxV;
  57093. //bleed over to face across v=0 edge (up)
  57094. bleedOverAmount[2] = (bboxSize - v);
  57095. bleedOverBBoxMin[2] = minU;
  57096. bleedOverBBoxMax[2] = maxU;
  57097. //bleed over to face across v=1 edge (down)
  57098. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  57099. bleedOverBBoxMin[3] = minU;
  57100. bleedOverBBoxMax[3] = maxU;
  57101. //compute bleed over regions in neighboring faces
  57102. for (var i = 0; i < 4; i++) {
  57103. if (bleedOverAmount[i] > 0) {
  57104. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  57105. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  57106. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  57107. // be flipped: the cases are
  57108. // if a left edge mates with a left or bottom edge on the neighbor
  57109. // if a top edge mates with a top or right edge on the neighbor
  57110. // if a right edge mates with a right or top edge on the neighbor
  57111. // if a bottom edge mates with a bottom or left edge on the neighbor
  57112. //Seeing as the edges are enumerated as follows
  57113. // left =0
  57114. // right =1
  57115. // top =2
  57116. // bottom =3
  57117. //
  57118. // so if the edge enums are the same, or the sum of the enums == 3,
  57119. // the bbox needs to be flipped
  57120. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  57121. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  57122. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  57123. }
  57124. //The way the bounding box is extended onto the neighboring face
  57125. // depends on which edge of neighboring face abuts with this one
  57126. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  57127. case PMREMGenerator.CP_EDGE_LEFT:
  57128. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  57129. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57130. break;
  57131. case PMREMGenerator.CP_EDGE_RIGHT:
  57132. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  57133. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  57134. break;
  57135. case PMREMGenerator.CP_EDGE_TOP:
  57136. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  57137. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  57138. break;
  57139. case PMREMGenerator.CP_EDGE_BOTTOM:
  57140. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  57141. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  57142. break;
  57143. }
  57144. //clamp filter extents in non-center tap faces to remain within surface
  57145. filterExtents[neighborFace].clampMin(0, 0, 0);
  57146. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  57147. }
  57148. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  57149. // from the center tap face, then process the opposite face entirely for now.
  57150. //Note that the cases in which this happens, what usually happens is that
  57151. // more than one edge bleeds onto the opposite face, and the bounding box
  57152. // encompasses the entire cube map face.
  57153. if (bleedOverAmount[i] > srcSize) {
  57154. //determine opposite face
  57155. switch (faceIdx) {
  57156. case PMREMGenerator.CP_FACE_X_POS:
  57157. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  57158. break;
  57159. case PMREMGenerator.CP_FACE_X_NEG:
  57160. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  57161. break;
  57162. case PMREMGenerator.CP_FACE_Y_POS:
  57163. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  57164. break;
  57165. case PMREMGenerator.CP_FACE_Y_NEG:
  57166. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  57167. break;
  57168. case PMREMGenerator.CP_FACE_Z_POS:
  57169. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  57170. break;
  57171. case PMREMGenerator.CP_FACE_Z_NEG:
  57172. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  57173. break;
  57174. default:
  57175. break;
  57176. }
  57177. //just encompass entire face for now
  57178. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  57179. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  57180. }
  57181. }
  57182. };
  57183. //--------------------------------------------------------------------------------------
  57184. //ProcessFilterExtents
  57185. // Process bounding box in each cube face
  57186. //
  57187. //--------------------------------------------------------------------------------------
  57188. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  57189. //accumulators are 64-bit floats in order to have the precision needed
  57190. // over a summation of a large number of pixels
  57191. var dstAccum = [0, 0, 0, 0];
  57192. var weightAccum = 0;
  57193. var k = 0;
  57194. var nSrcChannels = this.numChannels;
  57195. // norm cube map and srcCubeMap have same face width
  57196. var faceWidth = srcSize;
  57197. //amount to add to pointer to move to next scanline in images
  57198. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  57199. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  57200. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  57201. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  57202. // iterate over cubefaces
  57203. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  57204. //if bbox is non empty
  57205. if (!filterExtents[iFaceIdx].empty()) {
  57206. var uStart = filterExtents[iFaceIdx].min.x;
  57207. var vStart = filterExtents[iFaceIdx].min.y;
  57208. var uEnd = filterExtents[iFaceIdx].max.x;
  57209. var vEnd = filterExtents[iFaceIdx].max.y;
  57210. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  57211. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  57212. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  57213. for (var v = vStart; v <= vEnd; v++) {
  57214. var normCubeRowWalk = 0;
  57215. var srcCubeRowWalk = 0;
  57216. for (var u = uStart; u <= uEnd; u++) {
  57217. //pointer to direction in cube map associated with texel
  57218. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  57219. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  57220. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  57221. //check dot product to see if texel is within cone
  57222. var tapDotProd = texelVectX * centerTapDir.x +
  57223. texelVectY * centerTapDir.y +
  57224. texelVectZ * centerTapDir.z;
  57225. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  57226. //solid angle stored in 4th channel of normalizer/solid angle cube map
  57227. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  57228. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  57229. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  57230. // so just adding one to specularpower do the trick.
  57231. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  57232. //iterate over channels
  57233. for (k = 0; k < nSrcChannels; k++) {
  57234. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  57235. srcCubeRowWalk++;
  57236. }
  57237. weightAccum += weight; //accumulate weight
  57238. }
  57239. else {
  57240. //step across source pixel
  57241. srcCubeRowWalk += nSrcChannels;
  57242. }
  57243. normCubeRowWalk += 4; // 4 channels per norm cube map.
  57244. }
  57245. startIndexNormCubeMap += normCubePitch;
  57246. startIndexSrcCubeMap += srcCubePitch;
  57247. }
  57248. }
  57249. }
  57250. //divide through by weights if weight is non zero
  57251. if (weightAccum != 0.0) {
  57252. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  57253. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  57254. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  57255. if (this.numChannels > 3) {
  57256. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  57257. }
  57258. }
  57259. else {
  57260. // otherwise sample nearest
  57261. // get face idx and u, v texel coordinate in face
  57262. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  57263. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  57264. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  57265. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  57266. if (this.numChannels > 3) {
  57267. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  57268. }
  57269. }
  57270. return PMREMGenerator._vectorTemp;
  57271. };
  57272. //--------------------------------------------------------------------------------------
  57273. // Fixup cube edges
  57274. //
  57275. // average texels on cube map faces across the edges
  57276. // WARP/BENT Method Only.
  57277. //--------------------------------------------------------------------------------------
  57278. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  57279. var k;
  57280. var j;
  57281. var i;
  57282. var iFace;
  57283. var iCorner = 0;
  57284. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  57285. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  57286. // note that if functionality to filter across the three texels for each corner, then
  57287. //indexed by corner and face idx. the array contains the face the start points belongs to.
  57288. var cornerPtr = [
  57289. [[], [], []],
  57290. [[], [], []],
  57291. [[], [], []],
  57292. [[], [], []],
  57293. [[], [], []],
  57294. [[], [], []],
  57295. [[], [], []],
  57296. [[], [], []]
  57297. ];
  57298. //if there is no fixup, or fixup width = 0, do nothing
  57299. if (cubeMapSize < 1) {
  57300. return;
  57301. }
  57302. //special case 1x1 cubemap, average face colors
  57303. if (cubeMapSize == 1) {
  57304. //iterate over channels
  57305. for (k = 0; k < this.numChannels; k++) {
  57306. var accum = 0.0;
  57307. //iterate over faces to accumulate face colors
  57308. for (iFace = 0; iFace < 6; iFace++) {
  57309. accum += cubeMap[iFace][k];
  57310. }
  57311. //compute average over 6 face colors
  57312. accum /= 6.0;
  57313. //iterate over faces to distribute face colors
  57314. for (iFace = 0; iFace < 6; iFace++) {
  57315. cubeMap[iFace][k] = accum;
  57316. }
  57317. }
  57318. return;
  57319. }
  57320. //iterate over faces to collect list of corner texel pointers
  57321. for (iFace = 0; iFace < 6; iFace++) {
  57322. //the 4 corner pointers for this face
  57323. faceCornerStartIndicies[0] = [iFace, 0];
  57324. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  57325. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  57326. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  57327. //iterate over face corners to collect cube corner pointers
  57328. for (iCorner = 0; iCorner < 4; iCorner++) {
  57329. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  57330. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  57331. cornerNumPtrs[corner]++;
  57332. }
  57333. }
  57334. //iterate over corners to average across corner tap values
  57335. for (iCorner = 0; iCorner < 8; iCorner++) {
  57336. for (k = 0; k < this.numChannels; k++) {
  57337. var cornerTapAccum = 0.0;
  57338. //iterate over corner texels and average results
  57339. for (i = 0; i < 3; i++) {
  57340. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  57341. }
  57342. //divide by 3 to compute average of corner tap values
  57343. cornerTapAccum *= (1.0 / 3.0);
  57344. //iterate over corner texels and average results
  57345. for (i = 0; i < 3; i++) {
  57346. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  57347. }
  57348. }
  57349. }
  57350. //iterate over the twelve edges of the cube to average across edges
  57351. for (i = 0; i < 12; i++) {
  57352. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  57353. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  57354. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  57355. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  57356. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  57357. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  57358. var edgeWalk = 0;
  57359. var neighborEdgeWalk = 0;
  57360. //Determine walking pointers based on edge type
  57361. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  57362. switch (edge) {
  57363. case PMREMGenerator.CP_EDGE_LEFT:
  57364. // no change to faceEdgeStartPtr
  57365. edgeWalk = this.numChannels * cubeMapSize;
  57366. break;
  57367. case PMREMGenerator.CP_EDGE_RIGHT:
  57368. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57369. edgeWalk = this.numChannels * cubeMapSize;
  57370. break;
  57371. case PMREMGenerator.CP_EDGE_TOP:
  57372. // no change to faceEdgeStartPtr
  57373. edgeWalk = this.numChannels;
  57374. break;
  57375. case PMREMGenerator.CP_EDGE_BOTTOM:
  57376. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57377. edgeWalk = this.numChannels;
  57378. break;
  57379. }
  57380. //For certain types of edge abutments, the neighbor edge walk needs to
  57381. // be flipped: the cases are
  57382. // if a left edge mates with a left or bottom edge on the neighbor
  57383. // if a top edge mates with a top or right edge on the neighbor
  57384. // if a right edge mates with a right or top edge on the neighbor
  57385. // if a bottom edge mates with a bottom or left edge on the neighbor
  57386. //Seeing as the edges are enumerated as follows
  57387. // left =0
  57388. // right =1
  57389. // top =2
  57390. // bottom =3
  57391. //
  57392. //If the edge enums are the same, or the sum of the enums == 3,
  57393. // the neighbor edge walk needs to be flipped
  57394. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  57395. switch (neighborEdge) {
  57396. case PMREMGenerator.CP_EDGE_LEFT:
  57397. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  57398. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57399. break;
  57400. case PMREMGenerator.CP_EDGE_RIGHT:
  57401. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57402. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  57403. break;
  57404. case PMREMGenerator.CP_EDGE_TOP:
  57405. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57406. neighborEdgeWalk = -this.numChannels;
  57407. break;
  57408. case PMREMGenerator.CP_EDGE_BOTTOM:
  57409. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  57410. neighborEdgeWalk = -this.numChannels;
  57411. break;
  57412. }
  57413. }
  57414. else {
  57415. //swapped direction neighbor edge walk
  57416. switch (neighborEdge) {
  57417. case PMREMGenerator.CP_EDGE_LEFT:
  57418. //no change to neighborEdgeStartPtr for this case since it points
  57419. // to the upper left corner already
  57420. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57421. break;
  57422. case PMREMGenerator.CP_EDGE_RIGHT:
  57423. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  57424. neighborEdgeWalk = this.numChannels * cubeMapSize;
  57425. break;
  57426. case PMREMGenerator.CP_EDGE_TOP:
  57427. //no change to neighborEdgeStartPtr for this case since it points
  57428. // to the upper left corner already
  57429. neighborEdgeWalk = this.numChannels;
  57430. break;
  57431. case PMREMGenerator.CP_EDGE_BOTTOM:
  57432. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  57433. neighborEdgeWalk = this.numChannels;
  57434. break;
  57435. }
  57436. }
  57437. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  57438. //nearby neighborhood
  57439. //step ahead one texel on edge
  57440. edgeStartIndex += edgeWalk;
  57441. neighborEdgeStartIndex += neighborEdgeWalk;
  57442. // note that this loop does not process the corner texels, since they have already been
  57443. // averaged across faces across earlier
  57444. for (j = 1; j < (cubeMapSize - 1); j++) {
  57445. //for each set of taps along edge, average them
  57446. // and rewrite the results into the edges
  57447. for (k = 0; k < this.numChannels; k++) {
  57448. var edgeTap = cubeMap[face][edgeStartIndex + k];
  57449. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  57450. //compute average of tap intensity values
  57451. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  57452. //propagate average of taps to edge taps
  57453. cubeMap[face][edgeStartIndex + k] = avgTap;
  57454. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  57455. }
  57456. edgeStartIndex += edgeWalk;
  57457. neighborEdgeStartIndex += neighborEdgeWalk;
  57458. }
  57459. }
  57460. };
  57461. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  57462. PMREMGenerator.CP_UDIR = 0;
  57463. PMREMGenerator.CP_VDIR = 1;
  57464. PMREMGenerator.CP_FACEAXIS = 2;
  57465. //used to index cube faces
  57466. PMREMGenerator.CP_FACE_X_POS = 0;
  57467. PMREMGenerator.CP_FACE_X_NEG = 1;
  57468. PMREMGenerator.CP_FACE_Y_POS = 2;
  57469. PMREMGenerator.CP_FACE_Y_NEG = 3;
  57470. PMREMGenerator.CP_FACE_Z_POS = 4;
  57471. PMREMGenerator.CP_FACE_Z_NEG = 5;
  57472. //used to index image edges
  57473. // NOTE.. the actual number corresponding to the edge is important
  57474. // do not change these, or the code will break
  57475. //
  57476. // CP_EDGE_LEFT is u = 0
  57477. // CP_EDGE_RIGHT is u = width-1
  57478. // CP_EDGE_TOP is v = 0
  57479. // CP_EDGE_BOTTOM is v = height-1
  57480. PMREMGenerator.CP_EDGE_LEFT = 0;
  57481. PMREMGenerator.CP_EDGE_RIGHT = 1;
  57482. PMREMGenerator.CP_EDGE_TOP = 2;
  57483. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  57484. //corners of CUBE map (P or N specifys if it corresponds to the
  57485. // positive or negative direction each of X, Y, and Z
  57486. PMREMGenerator.CP_CORNER_NNN = 0;
  57487. PMREMGenerator.CP_CORNER_NNP = 1;
  57488. PMREMGenerator.CP_CORNER_NPN = 2;
  57489. PMREMGenerator.CP_CORNER_NPP = 3;
  57490. PMREMGenerator.CP_CORNER_PNN = 4;
  57491. PMREMGenerator.CP_CORNER_PNP = 5;
  57492. PMREMGenerator.CP_CORNER_PPN = 6;
  57493. PMREMGenerator.CP_CORNER_PPP = 7;
  57494. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  57495. //3x2 matrices that map cube map indexing vectors in 3d
  57496. // (after face selection and divide through by the
  57497. // _ABSOLUTE VALUE_ of the max coord)
  57498. // into NVC space
  57499. //Note this currently assumes the D3D cube face ordering and orientation
  57500. PMREMGenerator._sgFace2DMapping = [
  57501. //XPOS face
  57502. [[0, 0, -1],
  57503. [0, -1, 0],
  57504. [1, 0, 0]],
  57505. //XNEG face
  57506. [[0, 0, 1],
  57507. [0, -1, 0],
  57508. [-1, 0, 0]],
  57509. //YPOS face
  57510. [[1, 0, 0],
  57511. [0, 0, 1],
  57512. [0, 1, 0]],
  57513. //YNEG face
  57514. [[1, 0, 0],
  57515. [0, 0, -1],
  57516. [0, -1, 0]],
  57517. //ZPOS face
  57518. [[1, 0, 0],
  57519. [0, -1, 0],
  57520. [0, 0, 1]],
  57521. //ZNEG face
  57522. [[-1, 0, 0],
  57523. [0, -1, 0],
  57524. [0, 0, -1]],
  57525. ];
  57526. //------------------------------------------------------------------------------
  57527. // D3D cube map face specification
  57528. // mapping from 3D x,y,z cube map lookup coordinates
  57529. // to 2D within face u,v coordinates
  57530. //
  57531. // --------------------> U direction
  57532. // | (within-face texture space)
  57533. // | _____
  57534. // | | |
  57535. // | | +Y |
  57536. // | _____|_____|_____ _____
  57537. // | | | | | |
  57538. // | | -X | +Z | +X | -Z |
  57539. // | |_____|_____|_____|_____|
  57540. // | | |
  57541. // | | -Y |
  57542. // | |_____|
  57543. // |
  57544. // v V direction
  57545. // (within-face texture space)
  57546. //------------------------------------------------------------------------------
  57547. //Information about neighbors and how texture coorrdinates change across faces
  57548. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  57549. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  57550. //Note this currently assumes the D3D cube face ordering and orientation
  57551. PMREMGenerator._sgCubeNgh = [
  57552. //XPOS face
  57553. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57554. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57555. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57556. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  57557. //XNEG face
  57558. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57559. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  57560. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  57561. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  57562. //YPOS face
  57563. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57564. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57565. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57566. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  57567. //YNEG face
  57568. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57569. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57570. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57571. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  57572. //ZPOS face
  57573. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57574. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57575. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57576. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  57577. //ZNEG face
  57578. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57579. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57580. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  57581. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  57582. ];
  57583. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  57584. // this table is used to average over the edges.
  57585. PMREMGenerator._sgCubeEdgeList = [
  57586. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  57587. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  57588. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  57589. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57590. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  57591. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  57592. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  57593. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  57594. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  57595. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  57596. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  57597. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  57598. ];
  57599. //Information about which of the 8 cube corners are correspond to the
  57600. // the 4 corners in each cube face
  57601. // the order is upper left, upper right, lower left, lower right
  57602. PMREMGenerator._sgCubeCornerList = [
  57603. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  57604. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  57605. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  57606. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  57607. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  57608. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  57609. ];
  57610. return PMREMGenerator;
  57611. })();
  57612. Internals.PMREMGenerator = PMREMGenerator;
  57613. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57614. })(BABYLON || (BABYLON = {}));
  57615. var BABYLON;
  57616. (function (BABYLON) {
  57617. /**
  57618. * This represents a texture coming from an HDR input.
  57619. *
  57620. * The only supported format is currently panorama picture stored in RGBE format.
  57621. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57622. */
  57623. var HDRCubeTexture = (function (_super) {
  57624. __extends(HDRCubeTexture, _super);
  57625. /**
  57626. * Instantiates an HDRTexture from the following parameters.
  57627. *
  57628. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57629. * @param scene The scene the texture will be used in
  57630. * @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.
  57631. * @param noMipmap Forces to not generate the mipmap if true
  57632. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57633. * @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)
  57634. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57635. */
  57636. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  57637. if (noMipmap === void 0) { noMipmap = false; }
  57638. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57639. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57640. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57641. _super.call(this, scene);
  57642. this._useInGammaSpace = false;
  57643. this._generateHarmonics = true;
  57644. this._isBABYLONPreprocessed = false;
  57645. /**
  57646. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57647. */
  57648. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57649. /**
  57650. * The spherical polynomial data extracted from the texture.
  57651. */
  57652. this.sphericalPolynomial = null;
  57653. /**
  57654. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57655. * This is usefull at run time to apply the good shader.
  57656. */
  57657. this.isPMREM = false;
  57658. if (!url) {
  57659. return;
  57660. }
  57661. this.name = url;
  57662. this.url = url;
  57663. this.hasAlpha = false;
  57664. this.isCube = true;
  57665. this._textureMatrix = BABYLON.Matrix.Identity();
  57666. if (size) {
  57667. this._isBABYLONPreprocessed = false;
  57668. this._noMipmap = noMipmap;
  57669. this._size = size;
  57670. this._useInGammaSpace = useInGammaSpace;
  57671. this._usePMREMGenerator = usePMREMGenerator &&
  57672. scene.getEngine().getCaps().textureLOD &&
  57673. this.getScene().getEngine().getCaps().textureFloat &&
  57674. !this._useInGammaSpace;
  57675. }
  57676. else {
  57677. this._isBABYLONPreprocessed = true;
  57678. this._noMipmap = false;
  57679. this._useInGammaSpace = false;
  57680. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57681. this.getScene().getEngine().getCaps().textureFloat &&
  57682. !this._useInGammaSpace;
  57683. }
  57684. this.isPMREM = this._usePMREMGenerator;
  57685. this._texture = this._getFromCache(url, this._noMipmap);
  57686. if (!this._texture) {
  57687. if (!scene.useDelayedTextureLoading) {
  57688. this.loadTexture();
  57689. }
  57690. else {
  57691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57692. }
  57693. }
  57694. }
  57695. /**
  57696. * Occurs when the file is a preprocessed .babylon.hdr file.
  57697. */
  57698. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57699. var _this = this;
  57700. var mipLevels = 0;
  57701. var floatArrayView = null;
  57702. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57703. var mips = [];
  57704. var startIndex = 30;
  57705. for (var level = 0; level < mipLevels; level++) {
  57706. mips.push([]);
  57707. // Fill each pixel of the mip level.
  57708. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57709. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57710. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57711. mips[level].push(faceData);
  57712. startIndex += faceSize;
  57713. }
  57714. }
  57715. return mips;
  57716. } : null;
  57717. var callback = function (buffer) {
  57718. // Create Native Array Views
  57719. var intArrayView = new Int32Array(buffer);
  57720. floatArrayView = new Float32Array(buffer);
  57721. // Fill header.
  57722. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57723. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57724. // Update Texture Information.
  57725. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  57726. // Fill polynomial information.
  57727. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57728. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57729. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57730. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57731. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57732. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57733. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57734. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57735. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57736. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57737. // Fill pixel data.
  57738. mipLevels = intArrayView[29]; // Number of mip levels.
  57739. var startIndex = 30;
  57740. var data = [];
  57741. var faceSize = Math.pow(_this._size, 2) * 3;
  57742. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57743. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57744. startIndex += faceSize;
  57745. }
  57746. var results = [];
  57747. var byteArray = null;
  57748. // Push each faces.
  57749. for (var k = 0; k < 6; k++) {
  57750. var dataFace = null;
  57751. // If special cases.
  57752. if (!mipmapGenerator) {
  57753. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  57754. dataFace = data[j];
  57755. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57756. // 3 channels of 1 bytes per pixel in bytes.
  57757. var byteBuffer = new ArrayBuffer(faceSize);
  57758. byteArray = new Uint8Array(byteBuffer);
  57759. }
  57760. for (var i = 0; i < _this._size * _this._size; i++) {
  57761. // Put in gamma space if requested.
  57762. if (_this._useInGammaSpace) {
  57763. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57764. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57765. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57766. }
  57767. // Convert to int texture for fallback.
  57768. if (byteArray) {
  57769. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57770. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57771. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57772. // May use luminance instead if the result is not accurate.
  57773. var max = Math.max(Math.max(r, g), b);
  57774. if (max > 255) {
  57775. var scale = 255 / max;
  57776. r *= scale;
  57777. g *= scale;
  57778. b *= scale;
  57779. }
  57780. byteArray[(i * 3) + 0] = r;
  57781. byteArray[(i * 3) + 1] = g;
  57782. byteArray[(i * 3) + 2] = b;
  57783. }
  57784. }
  57785. }
  57786. else {
  57787. dataFace = data[k];
  57788. }
  57789. // Fill the array accordingly.
  57790. if (byteArray) {
  57791. results.push(byteArray);
  57792. }
  57793. else {
  57794. results.push(dataFace);
  57795. }
  57796. }
  57797. return results;
  57798. };
  57799. 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);
  57800. };
  57801. /**
  57802. * Occurs when the file is raw .hdr file.
  57803. */
  57804. HDRCubeTexture.prototype.loadHDRTexture = function () {
  57805. var _this = this;
  57806. var callback = function (buffer) {
  57807. // Extract the raw linear data.
  57808. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  57809. // Generate harmonics if needed.
  57810. if (_this._generateHarmonics) {
  57811. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  57812. }
  57813. var results = [];
  57814. var byteArray = null;
  57815. // Push each faces.
  57816. for (var j = 0; j < 6; j++) {
  57817. // Create uintarray fallback.
  57818. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57819. // 3 channels of 1 bytes per pixel in bytes.
  57820. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  57821. byteArray = new Uint8Array(byteBuffer);
  57822. }
  57823. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  57824. // If special cases.
  57825. if (_this._useInGammaSpace || byteArray) {
  57826. for (var i = 0; i < _this._size * _this._size; i++) {
  57827. // Put in gamma space if requested.
  57828. if (_this._useInGammaSpace) {
  57829. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57830. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57831. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57832. }
  57833. // Convert to int texture for fallback.
  57834. if (byteArray) {
  57835. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57836. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57837. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57838. // May use luminance instead if the result is not accurate.
  57839. var max = Math.max(Math.max(r, g), b);
  57840. if (max > 255) {
  57841. var scale = 255 / max;
  57842. r *= scale;
  57843. g *= scale;
  57844. b *= scale;
  57845. }
  57846. byteArray[(i * 3) + 0] = r;
  57847. byteArray[(i * 3) + 1] = g;
  57848. byteArray[(i * 3) + 2] = b;
  57849. }
  57850. }
  57851. }
  57852. if (byteArray) {
  57853. results.push(byteArray);
  57854. }
  57855. else {
  57856. results.push(dataFace);
  57857. }
  57858. }
  57859. return results;
  57860. };
  57861. var mipmapGenerator = null;
  57862. if (!this._noMipmap &&
  57863. this._usePMREMGenerator) {
  57864. mipmapGenerator = function (data) {
  57865. // Custom setup of the generator matching with the PBR shader values.
  57866. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  57867. return generator.filterCubeMap();
  57868. };
  57869. }
  57870. 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);
  57871. };
  57872. /**
  57873. * Starts the loading process of the texture.
  57874. */
  57875. HDRCubeTexture.prototype.loadTexture = function () {
  57876. if (this._isBABYLONPreprocessed) {
  57877. this.loadBabylonTexture();
  57878. }
  57879. else {
  57880. this.loadHDRTexture();
  57881. }
  57882. };
  57883. HDRCubeTexture.prototype.clone = function () {
  57884. var size = this._isBABYLONPreprocessed ? null : this._size;
  57885. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  57886. // Base texture
  57887. newTexture.level = this.level;
  57888. newTexture.wrapU = this.wrapU;
  57889. newTexture.wrapV = this.wrapV;
  57890. newTexture.coordinatesIndex = this.coordinatesIndex;
  57891. newTexture.coordinatesMode = this.coordinatesMode;
  57892. return newTexture;
  57893. };
  57894. // Methods
  57895. HDRCubeTexture.prototype.delayLoad = function () {
  57896. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57897. return;
  57898. }
  57899. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57900. this._texture = this._getFromCache(this.url, this._noMipmap);
  57901. if (!this._texture) {
  57902. this.loadTexture();
  57903. }
  57904. };
  57905. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  57906. return this._textureMatrix;
  57907. };
  57908. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57909. var texture = null;
  57910. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57911. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  57912. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  57913. texture.name = parsedTexture.name;
  57914. texture.hasAlpha = parsedTexture.hasAlpha;
  57915. texture.level = parsedTexture.level;
  57916. texture.coordinatesMode = parsedTexture.coordinatesMode;
  57917. }
  57918. return texture;
  57919. };
  57920. HDRCubeTexture.prototype.serialize = function () {
  57921. if (!this.name) {
  57922. return null;
  57923. }
  57924. var serializationObject = {};
  57925. serializationObject.name = this.name;
  57926. serializationObject.hasAlpha = this.hasAlpha;
  57927. serializationObject.isCube = true;
  57928. serializationObject.level = this.level;
  57929. serializationObject.size = this._size;
  57930. serializationObject.coordinatesMode = this.coordinatesMode;
  57931. serializationObject.useInGammaSpace = this._useInGammaSpace;
  57932. serializationObject.generateHarmonics = this._generateHarmonics;
  57933. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  57934. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  57935. serializationObject.customType = "BABYLON.HDRCubeTexture";
  57936. return serializationObject;
  57937. };
  57938. /**
  57939. * Saves as a file the data contained in the texture in a binary format.
  57940. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57941. * as the spherical used in the lighting.
  57942. * @param url The HDR file url.
  57943. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57944. * @param onError Method called if any error happens during download.
  57945. * @return The packed binary data.
  57946. */
  57947. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  57948. if (onError === void 0) { onError = null; }
  57949. var callback = function (buffer) {
  57950. var data = new Blob([buffer], { type: 'application/octet-stream' });
  57951. // Returns a URL you can use as a href.
  57952. var objUrl = window.URL.createObjectURL(data);
  57953. // Simulates a link to it and click to dowload.
  57954. var a = document.createElement("a");
  57955. document.body.appendChild(a);
  57956. a.style.display = "none";
  57957. a.href = objUrl;
  57958. a.download = "envmap.babylon.hdr";
  57959. a.click();
  57960. };
  57961. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  57962. };
  57963. /**
  57964. * Serializes the data contained in the texture in a binary format.
  57965. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  57966. * as the spherical used in the lighting.
  57967. * @param url The HDR file url.
  57968. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  57969. * @param onError Method called if any error happens during download.
  57970. * @return The packed binary data.
  57971. */
  57972. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  57973. if (onError === void 0) { onError = null; }
  57974. // Needs the url tho create the texture.
  57975. if (!url) {
  57976. return null;
  57977. }
  57978. // Check Power of two size.
  57979. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  57980. return null;
  57981. }
  57982. var getDataCallback = function (dataBuffer) {
  57983. // Extract the raw linear data.
  57984. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  57985. // Generate harmonics if needed.
  57986. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  57987. // Generate seamless faces
  57988. var mipGeneratorArray = [];
  57989. // Data are known to be in +X +Y +Z -X -Y -Z
  57990. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  57991. mipGeneratorArray.push(cubeData.right); // +X
  57992. mipGeneratorArray.push(cubeData.left); // -X
  57993. mipGeneratorArray.push(cubeData.up); // +Y
  57994. mipGeneratorArray.push(cubeData.down); // -Y
  57995. mipGeneratorArray.push(cubeData.front); // +Z
  57996. mipGeneratorArray.push(cubeData.back); // -Z
  57997. // Custom setup of the generator matching with the PBR shader values.
  57998. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  57999. var mippedData = generator.filterCubeMap();
  58000. // Compute required byte length.
  58001. var byteLength = 1 * 4; // Raw Data Version int32.
  58002. byteLength += 4; // CubeMap max mip face size int32.
  58003. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  58004. // Add data size.
  58005. byteLength += 4; // Number of mip levels int32.
  58006. for (var level = 0; level < mippedData.length; level++) {
  58007. var mipSize = size >> level;
  58008. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  58009. }
  58010. // Prepare binary structure.
  58011. var buffer = new ArrayBuffer(byteLength);
  58012. var intArrayView = new Int32Array(buffer);
  58013. var floatArrayView = new Float32Array(buffer);
  58014. // Fill header.
  58015. intArrayView[0] = 1; // Version 1.
  58016. intArrayView[1] = size; // CubeMap max mip face size.
  58017. // Fill polynomial information.
  58018. sphericalPolynomial.x.toArray(floatArrayView, 2);
  58019. sphericalPolynomial.y.toArray(floatArrayView, 5);
  58020. sphericalPolynomial.z.toArray(floatArrayView, 8);
  58021. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  58022. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  58023. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  58024. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  58025. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  58026. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  58027. // Fill pixel data.
  58028. intArrayView[29] = mippedData.length; // Number of mip levels.
  58029. var startIndex = 30;
  58030. for (var level = 0; level < mippedData.length; level++) {
  58031. // Fill each pixel of the mip level.
  58032. var faceSize = Math.pow(size >> level, 2) * 3;
  58033. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58034. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  58035. startIndex += faceSize;
  58036. }
  58037. }
  58038. // Callback.
  58039. callback(buffer);
  58040. };
  58041. // Download and process.
  58042. BABYLON.Tools.LoadFile(url, function (data) {
  58043. getDataCallback(data);
  58044. }, null, null, true, onError);
  58045. };
  58046. HDRCubeTexture._facesMapping = [
  58047. "right",
  58048. "up",
  58049. "front",
  58050. "left",
  58051. "down",
  58052. "back"
  58053. ];
  58054. return HDRCubeTexture;
  58055. })(BABYLON.BaseTexture);
  58056. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58057. })(BABYLON || (BABYLON = {}));
  58058. var BABYLON;
  58059. (function (BABYLON) {
  58060. var Debug;
  58061. (function (Debug) {
  58062. /**
  58063. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  58064. */
  58065. var SkeletonViewer = (function () {
  58066. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  58067. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58068. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58069. this.skeleton = skeleton;
  58070. this.mesh = mesh;
  58071. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58072. this.renderingGroupId = renderingGroupId;
  58073. this.color = BABYLON.Color3.White();
  58074. this._debugLines = [];
  58075. this._isEnabled = false;
  58076. this._scene = scene;
  58077. this.update();
  58078. this._renderFunction = this.update.bind(this);
  58079. }
  58080. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58081. get: function () {
  58082. return this._isEnabled;
  58083. },
  58084. set: function (value) {
  58085. if (this._isEnabled === value) {
  58086. return;
  58087. }
  58088. this._isEnabled = value;
  58089. if (value) {
  58090. this._scene.registerBeforeRender(this._renderFunction);
  58091. }
  58092. else {
  58093. this._scene.unregisterBeforeRender(this._renderFunction);
  58094. }
  58095. },
  58096. enumerable: true,
  58097. configurable: true
  58098. });
  58099. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58100. if (x === void 0) { x = 0; }
  58101. if (y === void 0) { y = 0; }
  58102. if (z === void 0) { z = 0; }
  58103. var tmat = BABYLON.Tmp.Matrix[0];
  58104. var parentBone = bone.getParent();
  58105. tmat.copyFrom(bone.getLocalMatrix());
  58106. if (x !== 0 || y !== 0 || z !== 0) {
  58107. var tmat2 = BABYLON.Tmp.Matrix[1];
  58108. BABYLON.Matrix.IdentityToRef(tmat2);
  58109. tmat2.m[12] = x;
  58110. tmat2.m[13] = y;
  58111. tmat2.m[14] = z;
  58112. tmat2.multiplyToRef(tmat, tmat);
  58113. }
  58114. if (parentBone) {
  58115. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58116. }
  58117. tmat.multiplyToRef(meshMat, tmat);
  58118. position.x = tmat.m[12];
  58119. position.y = tmat.m[13];
  58120. position.z = tmat.m[14];
  58121. };
  58122. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58123. var len = bones.length;
  58124. for (var i = 0; i < len; i++) {
  58125. var bone = bones[i];
  58126. var points = this._debugLines[i];
  58127. if (!points) {
  58128. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58129. this._debugLines[i] = points;
  58130. }
  58131. this._getBonePosition(points[0], bone, meshMat);
  58132. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58133. }
  58134. };
  58135. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58136. var len = bones.length;
  58137. var boneNum = 0;
  58138. for (var i = len - 1; i >= 0; i--) {
  58139. var childBone = bones[i];
  58140. var parentBone = childBone.getParent();
  58141. if (!parentBone) {
  58142. continue;
  58143. }
  58144. var points = this._debugLines[boneNum];
  58145. if (!points) {
  58146. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58147. this._debugLines[boneNum] = points;
  58148. }
  58149. this._getBonePosition(points[0], childBone, meshMat);
  58150. this._getBonePosition(points[1], parentBone, meshMat);
  58151. boneNum++;
  58152. }
  58153. };
  58154. SkeletonViewer.prototype.update = function () {
  58155. if (this.autoUpdateBonesMatrices) {
  58156. this._updateBoneMatrix(this.skeleton.bones[0]);
  58157. }
  58158. if (this.skeleton.bones[0].length === undefined) {
  58159. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58160. }
  58161. else {
  58162. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58163. }
  58164. if (!this._debugMesh) {
  58165. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  58166. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58167. }
  58168. else {
  58169. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58170. }
  58171. this._debugMesh.color = this.color;
  58172. };
  58173. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  58174. if (bone.getParent()) {
  58175. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  58176. }
  58177. var children = bone.children;
  58178. var len = children.length;
  58179. for (var i = 0; i < len; i++) {
  58180. this._updateBoneMatrix(children[i]);
  58181. }
  58182. };
  58183. SkeletonViewer.prototype.dispose = function () {
  58184. if (this._debugMesh) {
  58185. this.isEnabled = false;
  58186. this._debugMesh.dispose();
  58187. this._debugMesh = null;
  58188. }
  58189. };
  58190. return SkeletonViewer;
  58191. })();
  58192. Debug.SkeletonViewer = SkeletonViewer;
  58193. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58194. })(BABYLON || (BABYLON = {}));
  58195. var BABYLON;
  58196. (function (BABYLON) {
  58197. /**
  58198. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58199. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58200. * 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;
  58201. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58202. */
  58203. var ColorCurves = (function () {
  58204. function ColorCurves() {
  58205. this._dirty = true;
  58206. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  58207. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  58208. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58209. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  58210. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  58211. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  58212. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  58213. this._globalHue = 30;
  58214. this._globalDensity = 0;
  58215. this._globalSaturation = 0;
  58216. this._globalExposure = 0;
  58217. this._highlightsHue = 30;
  58218. this._highlightsDensity = 0;
  58219. this._highlightsSaturation = 0;
  58220. this._highlightsExposure = 0;
  58221. this._midtonesHue = 30;
  58222. this._midtonesDensity = 0;
  58223. this._midtonesSaturation = 0;
  58224. this._midtonesExposure = 0;
  58225. this._shadowsHue = 30;
  58226. this._shadowsDensity = 0;
  58227. this._shadowsSaturation = 0;
  58228. this._shadowsExposure = 0;
  58229. }
  58230. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  58231. /**
  58232. * Gets the global Hue value.
  58233. * 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).
  58234. */
  58235. get: function () {
  58236. return this._globalHue;
  58237. },
  58238. /**
  58239. * Sets the global Hue value.
  58240. * 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).
  58241. */
  58242. set: function (value) {
  58243. this._globalHue = value;
  58244. this._dirty = true;
  58245. },
  58246. enumerable: true,
  58247. configurable: true
  58248. });
  58249. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  58250. /**
  58251. * Gets the global Density value.
  58252. * 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.
  58253. * Values less than zero provide a filter of opposite hue.
  58254. */
  58255. get: function () {
  58256. return this._globalDensity;
  58257. },
  58258. /**
  58259. * Sets the global Density value.
  58260. * 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.
  58261. * Values less than zero provide a filter of opposite hue.
  58262. */
  58263. set: function (value) {
  58264. this._globalDensity = value;
  58265. this._dirty = true;
  58266. },
  58267. enumerable: true,
  58268. configurable: true
  58269. });
  58270. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  58271. /**
  58272. * Gets the global Saturation value.
  58273. * 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.
  58274. */
  58275. get: function () {
  58276. return this._globalSaturation;
  58277. },
  58278. /**
  58279. * Sets the global Saturation value.
  58280. * 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.
  58281. */
  58282. set: function (value) {
  58283. this._globalSaturation = value;
  58284. this._dirty = true;
  58285. },
  58286. enumerable: true,
  58287. configurable: true
  58288. });
  58289. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  58290. /**
  58291. * Gets the highlights Hue value.
  58292. * 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).
  58293. */
  58294. get: function () {
  58295. return this._highlightsHue;
  58296. },
  58297. /**
  58298. * Sets the highlights Hue value.
  58299. * 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).
  58300. */
  58301. set: function (value) {
  58302. this._highlightsHue = value;
  58303. this._dirty = true;
  58304. },
  58305. enumerable: true,
  58306. configurable: true
  58307. });
  58308. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  58309. /**
  58310. * Gets the highlights Density value.
  58311. * 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.
  58312. * Values less than zero provide a filter of opposite hue.
  58313. */
  58314. get: function () {
  58315. return this._highlightsDensity;
  58316. },
  58317. /**
  58318. * Sets the highlights Density value.
  58319. * 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.
  58320. * Values less than zero provide a filter of opposite hue.
  58321. */
  58322. set: function (value) {
  58323. this._highlightsDensity = value;
  58324. this._dirty = true;
  58325. },
  58326. enumerable: true,
  58327. configurable: true
  58328. });
  58329. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  58330. /**
  58331. * Gets the highlights Saturation value.
  58332. * 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.
  58333. */
  58334. get: function () {
  58335. return this._highlightsSaturation;
  58336. },
  58337. /**
  58338. * Sets the highlights Saturation value.
  58339. * 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.
  58340. */
  58341. set: function (value) {
  58342. this._highlightsSaturation = value;
  58343. this._dirty = true;
  58344. },
  58345. enumerable: true,
  58346. configurable: true
  58347. });
  58348. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  58349. /**
  58350. * Gets the highlights Exposure value.
  58351. * 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.
  58352. */
  58353. get: function () {
  58354. return this._highlightsExposure;
  58355. },
  58356. /**
  58357. * Sets the highlights Exposure value.
  58358. * 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.
  58359. */
  58360. set: function (value) {
  58361. this._highlightsExposure = value;
  58362. this._dirty = true;
  58363. },
  58364. enumerable: true,
  58365. configurable: true
  58366. });
  58367. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  58368. /**
  58369. * Gets the midtones Hue value.
  58370. * 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).
  58371. */
  58372. get: function () {
  58373. return this._midtonesHue;
  58374. },
  58375. /**
  58376. * Sets the midtones Hue value.
  58377. * 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).
  58378. */
  58379. set: function (value) {
  58380. this._midtonesHue = value;
  58381. this._dirty = true;
  58382. },
  58383. enumerable: true,
  58384. configurable: true
  58385. });
  58386. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  58387. /**
  58388. * Gets the midtones Density value.
  58389. * 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.
  58390. * Values less than zero provide a filter of opposite hue.
  58391. */
  58392. get: function () {
  58393. return this._midtonesDensity;
  58394. },
  58395. /**
  58396. * Sets the midtones Density value.
  58397. * 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.
  58398. * Values less than zero provide a filter of opposite hue.
  58399. */
  58400. set: function (value) {
  58401. this._midtonesDensity = value;
  58402. this._dirty = true;
  58403. },
  58404. enumerable: true,
  58405. configurable: true
  58406. });
  58407. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  58408. /**
  58409. * Gets the midtones Saturation value.
  58410. * 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.
  58411. */
  58412. get: function () {
  58413. return this._midtonesSaturation;
  58414. },
  58415. /**
  58416. * Sets the midtones Saturation value.
  58417. * 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.
  58418. */
  58419. set: function (value) {
  58420. this._midtonesSaturation = value;
  58421. this._dirty = true;
  58422. },
  58423. enumerable: true,
  58424. configurable: true
  58425. });
  58426. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  58427. /**
  58428. * Gets the midtones Exposure value.
  58429. * 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.
  58430. */
  58431. get: function () {
  58432. return this._midtonesExposure;
  58433. },
  58434. /**
  58435. * Sets the midtones Exposure value.
  58436. * 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.
  58437. */
  58438. set: function (value) {
  58439. this._midtonesExposure = value;
  58440. this._dirty = true;
  58441. },
  58442. enumerable: true,
  58443. configurable: true
  58444. });
  58445. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  58446. /**
  58447. * Gets the shadows Hue value.
  58448. * 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).
  58449. */
  58450. get: function () {
  58451. return this._shadowsHue;
  58452. },
  58453. /**
  58454. * Sets the shadows Hue value.
  58455. * 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).
  58456. */
  58457. set: function (value) {
  58458. this._shadowsHue = value;
  58459. this._dirty = true;
  58460. },
  58461. enumerable: true,
  58462. configurable: true
  58463. });
  58464. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  58465. /**
  58466. * Gets the shadows Density value.
  58467. * 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.
  58468. * Values less than zero provide a filter of opposite hue.
  58469. */
  58470. get: function () {
  58471. return this._shadowsDensity;
  58472. },
  58473. /**
  58474. * Sets the shadows Density value.
  58475. * 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.
  58476. * Values less than zero provide a filter of opposite hue.
  58477. */
  58478. set: function (value) {
  58479. this._shadowsDensity = value;
  58480. this._dirty = true;
  58481. },
  58482. enumerable: true,
  58483. configurable: true
  58484. });
  58485. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  58486. /**
  58487. * Gets the shadows Saturation value.
  58488. * 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.
  58489. */
  58490. get: function () {
  58491. return this._shadowsSaturation;
  58492. },
  58493. /**
  58494. * Sets the shadows Saturation value.
  58495. * 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.
  58496. */
  58497. set: function (value) {
  58498. this._shadowsSaturation = value;
  58499. this._dirty = true;
  58500. },
  58501. enumerable: true,
  58502. configurable: true
  58503. });
  58504. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  58505. /**
  58506. * Gets the shadows Exposure value.
  58507. * 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.
  58508. */
  58509. get: function () {
  58510. return this._shadowsExposure;
  58511. },
  58512. /**
  58513. * Sets the shadows Exposure value.
  58514. * 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.
  58515. */
  58516. set: function (value) {
  58517. this._shadowsExposure = value;
  58518. this._dirty = true;
  58519. },
  58520. enumerable: true,
  58521. configurable: true
  58522. });
  58523. /**
  58524. * Binds the color curves to the shader.
  58525. * @param colorCurves The color curve to bind
  58526. * @param effect The effect to bind to
  58527. */
  58528. ColorCurves.Bind = function (colorCurves, effect) {
  58529. if (colorCurves._dirty) {
  58530. colorCurves._dirty = false;
  58531. // Fill in global info.
  58532. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  58533. // Compute highlights info.
  58534. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  58535. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  58536. // Compute midtones info.
  58537. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  58538. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  58539. // Compute shadows info.
  58540. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  58541. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  58542. // Compute deltas (neutral is midtones).
  58543. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  58544. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  58545. }
  58546. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  58547. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  58548. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  58549. };
  58550. /**
  58551. * Prepare the list of uniforms associated with the ColorCurves effects.
  58552. * @param uniformsList The list of uniforms used in the effect
  58553. */
  58554. ColorCurves.PrepareUniforms = function (uniformsList) {
  58555. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  58556. };
  58557. /**
  58558. * Returns color grading data based on a hue, density, saturation and exposure value.
  58559. * @param filterHue The hue of the color filter.
  58560. * @param filterDensity The density of the color filter.
  58561. * @param saturation The saturation.
  58562. * @param exposure The exposure.
  58563. * @param result The result data container.
  58564. */
  58565. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  58566. if (hue == null) {
  58567. return;
  58568. }
  58569. hue = ColorCurves.clamp(hue, 0, 360);
  58570. density = ColorCurves.clamp(density, -100, 100);
  58571. saturation = ColorCurves.clamp(saturation, -100, 100);
  58572. exposure = ColorCurves.clamp(exposure, -100, 100);
  58573. // Remap the slider/config filter density with non-linear mapping and also scale by half
  58574. // so that the maximum filter density is only 50% control. This provides fine control
  58575. // for small values and reasonable range.
  58576. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  58577. density *= 0.5;
  58578. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  58579. if (density < 0) {
  58580. density *= -1;
  58581. hue = (hue + 180) % 360;
  58582. }
  58583. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  58584. result.scaleToRef(2, result);
  58585. result.a = 1 + 0.01 * saturation;
  58586. };
  58587. /**
  58588. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  58589. * @param value The input slider value in range [-100,100].
  58590. * @returns Adjusted value.
  58591. */
  58592. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  58593. value /= 100;
  58594. var x = Math.abs(value);
  58595. x = Math.pow(x, 2);
  58596. if (value < 0) {
  58597. x *= -1;
  58598. }
  58599. x *= 100;
  58600. return x;
  58601. };
  58602. /**
  58603. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  58604. * @param hue The hue (H) input.
  58605. * @param saturation The saturation (S) input.
  58606. * @param brightness The brightness (B) input.
  58607. * @result An RGBA color represented as Vector4.
  58608. */
  58609. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  58610. var h = ColorCurves.clamp(hue, 0, 360);
  58611. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  58612. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  58613. if (s === 0) {
  58614. result.r = v;
  58615. result.g = v;
  58616. result.b = v;
  58617. }
  58618. else {
  58619. // sector 0 to 5
  58620. h /= 60;
  58621. var i = Math.floor(h);
  58622. // fractional part of h
  58623. var f = h - i;
  58624. var p = v * (1 - s);
  58625. var q = v * (1 - s * f);
  58626. var t = v * (1 - s * (1 - f));
  58627. switch (i) {
  58628. case 0:
  58629. result.r = v;
  58630. result.g = t;
  58631. result.b = p;
  58632. break;
  58633. case 1:
  58634. result.r = q;
  58635. result.g = v;
  58636. result.b = p;
  58637. break;
  58638. case 2:
  58639. result.r = p;
  58640. result.g = v;
  58641. result.b = t;
  58642. break;
  58643. case 3:
  58644. result.r = p;
  58645. result.g = q;
  58646. result.b = v;
  58647. break;
  58648. case 4:
  58649. result.r = t;
  58650. result.g = p;
  58651. result.b = v;
  58652. break;
  58653. default:
  58654. result.r = v;
  58655. result.g = p;
  58656. result.b = q;
  58657. break;
  58658. }
  58659. }
  58660. result.a = 1;
  58661. };
  58662. /**
  58663. * Returns a value clamped between min and max
  58664. * @param value The value to clamp
  58665. * @param min The minimum of value
  58666. * @param max The maximum of value
  58667. * @returns The clamped value.
  58668. */
  58669. ColorCurves.clamp = function (value, min, max) {
  58670. return Math.min(Math.max(value, min), max);
  58671. };
  58672. /**
  58673. * Clones the current color curve instance.
  58674. * @return The cloned curves
  58675. */
  58676. ColorCurves.prototype.clone = function () {
  58677. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  58678. };
  58679. /**
  58680. * Serializes the current color curve instance to a json representation.
  58681. * @return a JSON representation
  58682. */
  58683. ColorCurves.prototype.serialize = function () {
  58684. return BABYLON.SerializationHelper.Serialize(this);
  58685. };
  58686. /**
  58687. * Parses the color curve from a json representation.
  58688. * @param source the JSON source to parse
  58689. * @return The parsed curves
  58690. */
  58691. ColorCurves.Parse = function (source) {
  58692. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  58693. };
  58694. __decorate([
  58695. BABYLON.serialize()
  58696. ], ColorCurves.prototype, "_globalHue", void 0);
  58697. __decorate([
  58698. BABYLON.serialize()
  58699. ], ColorCurves.prototype, "_globalDensity", void 0);
  58700. __decorate([
  58701. BABYLON.serialize()
  58702. ], ColorCurves.prototype, "_globalSaturation", void 0);
  58703. __decorate([
  58704. BABYLON.serialize()
  58705. ], ColorCurves.prototype, "_globalExposure", void 0);
  58706. __decorate([
  58707. BABYLON.serialize()
  58708. ], ColorCurves.prototype, "_highlightsHue", void 0);
  58709. __decorate([
  58710. BABYLON.serialize()
  58711. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  58712. __decorate([
  58713. BABYLON.serialize()
  58714. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  58715. __decorate([
  58716. BABYLON.serialize()
  58717. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  58718. __decorate([
  58719. BABYLON.serialize()
  58720. ], ColorCurves.prototype, "_midtonesHue", void 0);
  58721. __decorate([
  58722. BABYLON.serialize()
  58723. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  58724. __decorate([
  58725. BABYLON.serialize()
  58726. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  58727. __decorate([
  58728. BABYLON.serialize()
  58729. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  58730. return ColorCurves;
  58731. })();
  58732. BABYLON.ColorCurves = ColorCurves;
  58733. })(BABYLON || (BABYLON = {}));
  58734. var BABYLON;
  58735. (function (BABYLON) {
  58736. /**
  58737. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  58738. * It can help converting any input color in a desired output one. This can then be used to create effects
  58739. * from sepia, black and white to sixties or futuristic rendering...
  58740. *
  58741. * The only supported format is currently 3dl.
  58742. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  58743. */
  58744. var ColorGradingTexture = (function (_super) {
  58745. __extends(ColorGradingTexture, _super);
  58746. /**
  58747. * Instantiates a ColorGradingTexture from the following parameters.
  58748. *
  58749. * @param url The location of the color gradind data (currently only supporting 3dl)
  58750. * @param scene The scene the texture will be used in
  58751. */
  58752. function ColorGradingTexture(url, scene) {
  58753. _super.call(this, scene);
  58754. if (!url) {
  58755. return;
  58756. }
  58757. this._textureMatrix = BABYLON.Matrix.Identity();
  58758. this.name = url;
  58759. this.url = url;
  58760. this.hasAlpha = false;
  58761. this.isCube = false;
  58762. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58763. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58764. this.anisotropicFilteringLevel = 1;
  58765. this._texture = this._getFromCache(url, true);
  58766. if (!this._texture) {
  58767. if (!scene.useDelayedTextureLoading) {
  58768. this.loadTexture();
  58769. }
  58770. else {
  58771. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58772. }
  58773. }
  58774. }
  58775. /**
  58776. * Returns the texture matrix used in most of the material.
  58777. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  58778. */
  58779. ColorGradingTexture.prototype.getTextureMatrix = function () {
  58780. return this._textureMatrix;
  58781. };
  58782. /**
  58783. * Occurs when the file being loaded is a .3dl LUT file.
  58784. */
  58785. ColorGradingTexture.prototype.load3dlTexture = function () {
  58786. var _this = this;
  58787. var mipLevels = 0;
  58788. var floatArrayView = null;
  58789. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58790. this._texture = texture;
  58791. var callback = function (text) {
  58792. var data;
  58793. var tempData;
  58794. var line;
  58795. var lines = text.split('\n');
  58796. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  58797. var maxColor = 0;
  58798. for (var i = 0; i < lines.length; i++) {
  58799. line = lines[i];
  58800. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  58801. continue;
  58802. if (line.indexOf('#') === 0)
  58803. continue;
  58804. var words = line.split(" ");
  58805. if (size === 0) {
  58806. // Number of space + one
  58807. size = words.length;
  58808. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  58809. tempData = new Float32Array(size * size * size * 4);
  58810. continue;
  58811. }
  58812. if (size != 0) {
  58813. var r = Math.max(parseInt(words[0]), 0);
  58814. var g = Math.max(parseInt(words[1]), 0);
  58815. var b = Math.max(parseInt(words[2]), 0);
  58816. maxColor = Math.max(r, maxColor);
  58817. maxColor = Math.max(g, maxColor);
  58818. maxColor = Math.max(b, maxColor);
  58819. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  58820. tempData[pixelStorageIndex + 0] = r;
  58821. tempData[pixelStorageIndex + 1] = g;
  58822. tempData[pixelStorageIndex + 2] = b;
  58823. tempData[pixelStorageIndex + 3] = 0;
  58824. pixelIndexSlice++;
  58825. if (pixelIndexSlice % size == 0) {
  58826. pixelIndexH++;
  58827. pixelIndexSlice = 0;
  58828. if (pixelIndexH % size == 0) {
  58829. pixelIndexW++;
  58830. pixelIndexH = 0;
  58831. }
  58832. }
  58833. }
  58834. }
  58835. for (var i = 0; i < tempData.length; i++) {
  58836. var value = tempData[i];
  58837. data[i] = (value / maxColor * 255);
  58838. }
  58839. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  58840. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  58841. };
  58842. BABYLON.Tools.LoadFile(this.url, callback);
  58843. return this._texture;
  58844. };
  58845. /**
  58846. * Starts the loading process of the texture.
  58847. */
  58848. ColorGradingTexture.prototype.loadTexture = function () {
  58849. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  58850. this.load3dlTexture();
  58851. }
  58852. };
  58853. /**
  58854. * Clones the color gradind texture.
  58855. */
  58856. ColorGradingTexture.prototype.clone = function () {
  58857. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  58858. // Base texture
  58859. newTexture.level = this.level;
  58860. return newTexture;
  58861. };
  58862. /**
  58863. * Called during delayed load for textures.
  58864. */
  58865. ColorGradingTexture.prototype.delayLoad = function () {
  58866. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58867. return;
  58868. }
  58869. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58870. this._texture = this._getFromCache(this.url, true);
  58871. if (!this._texture) {
  58872. this.loadTexture();
  58873. }
  58874. };
  58875. /**
  58876. * Binds the color grading to the shader.
  58877. * @param colorGrading The texture to bind
  58878. * @param effect The effect to bind to
  58879. */
  58880. ColorGradingTexture.Bind = function (colorGrading, effect) {
  58881. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  58882. var x = colorGrading.level; // Texture Level
  58883. var y = colorGrading.getSize().height; // Texture Size example with 8
  58884. var z = y - 1.0; // SizeMinusOne 8 - 1
  58885. var w = 1 / y; // Space of 1 slice 1 / 8
  58886. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  58887. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  58888. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  58889. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  58890. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  58891. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  58892. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  58893. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  58894. };
  58895. /**
  58896. * Prepare the list of uniforms associated with the ColorGrading effects.
  58897. * @param uniformsList The list of uniforms used in the effect
  58898. * @param samplersList The list of samplers used in the effect
  58899. */
  58900. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  58901. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  58902. samplersList.push("cameraColorGrading2DSampler");
  58903. };
  58904. /**
  58905. * Parses a color grading texture serialized by Babylon.
  58906. * @param parsedTexture The texture information being parsedTexture
  58907. * @param scene The scene to load the texture in
  58908. * @param rootUrl The root url of the data assets to load
  58909. * @return A color gradind texture
  58910. */
  58911. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58912. var texture = null;
  58913. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58914. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  58915. texture.name = parsedTexture.name;
  58916. texture.level = parsedTexture.level;
  58917. }
  58918. return texture;
  58919. };
  58920. /**
  58921. * Serializes the LUT texture to json format.
  58922. */
  58923. ColorGradingTexture.prototype.serialize = function () {
  58924. if (!this.name) {
  58925. return null;
  58926. }
  58927. var serializationObject = {};
  58928. serializationObject.name = this.name;
  58929. serializationObject.level = this.level;
  58930. serializationObject.customType = "BABYLON.ColorGradingTexture";
  58931. return serializationObject;
  58932. };
  58933. /**
  58934. * Empty line regex stored for GC.
  58935. */
  58936. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  58937. return ColorGradingTexture;
  58938. })(BABYLON.BaseTexture);
  58939. BABYLON.ColorGradingTexture = ColorGradingTexture;
  58940. })(BABYLON || (BABYLON = {}));
  58941. var BABYLON;
  58942. (function (BABYLON) {
  58943. var PBRMaterialDefines = (function (_super) {
  58944. __extends(PBRMaterialDefines, _super);
  58945. function PBRMaterialDefines() {
  58946. _super.call(this);
  58947. this.ALBEDO = false;
  58948. this.AMBIENT = false;
  58949. this.OPACITY = false;
  58950. this.OPACITYRGB = false;
  58951. this.REFLECTION = false;
  58952. this.EMISSIVE = false;
  58953. this.REFLECTIVITY = false;
  58954. this.BUMP = false;
  58955. this.PARALLAX = false;
  58956. this.PARALLAXOCCLUSION = false;
  58957. this.SPECULAROVERALPHA = false;
  58958. this.CLIPPLANE = false;
  58959. this.ALPHATEST = false;
  58960. this.ALPHAFROMALBEDO = false;
  58961. this.POINTSIZE = false;
  58962. this.FOG = false;
  58963. this.SPECULARTERM = false;
  58964. this.OPACITYFRESNEL = false;
  58965. this.EMISSIVEFRESNEL = false;
  58966. this.FRESNEL = false;
  58967. this.NORMAL = false;
  58968. this.UV1 = false;
  58969. this.UV2 = false;
  58970. this.VERTEXCOLOR = false;
  58971. this.VERTEXALPHA = false;
  58972. this.NUM_BONE_INFLUENCERS = 0;
  58973. this.BonesPerMesh = 0;
  58974. this.INSTANCES = false;
  58975. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  58976. this.MICROSURFACEAUTOMATIC = false;
  58977. this.EMISSIVEASILLUMINATION = false;
  58978. this.LINKEMISSIVEWITHALBEDO = false;
  58979. this.LIGHTMAP = false;
  58980. this.USELIGHTMAPASSHADOWMAP = false;
  58981. this.REFLECTIONMAP_3D = false;
  58982. this.REFLECTIONMAP_SPHERICAL = false;
  58983. this.REFLECTIONMAP_PLANAR = false;
  58984. this.REFLECTIONMAP_CUBIC = false;
  58985. this.REFLECTIONMAP_PROJECTION = false;
  58986. this.REFLECTIONMAP_SKYBOX = false;
  58987. this.REFLECTIONMAP_EXPLICIT = false;
  58988. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  58989. this.INVERTCUBICMAP = false;
  58990. this.LOGARITHMICDEPTH = false;
  58991. this.CAMERATONEMAP = false;
  58992. this.CAMERACONTRAST = false;
  58993. this.CAMERACOLORGRADING = false;
  58994. this.CAMERACOLORCURVES = false;
  58995. this.OVERLOADEDVALUES = false;
  58996. this.OVERLOADEDSHADOWVALUES = false;
  58997. this.USESPHERICALFROMREFLECTIONMAP = false;
  58998. this.REFRACTION = false;
  58999. this.REFRACTIONMAP_3D = false;
  59000. this.LINKREFRACTIONTOTRANSPARENCY = false;
  59001. this.REFRACTIONMAPINLINEARSPACE = false;
  59002. this.LODBASEDMICROSFURACE = false;
  59003. this.USEPHYSICALLIGHTFALLOFF = false;
  59004. this.RADIANCEOVERALPHA = false;
  59005. this.USEPMREMREFLECTION = false;
  59006. this.USEPMREMREFRACTION = false;
  59007. this.OPENGLNORMALMAP = false;
  59008. this.INVERTNORMALMAPX = false;
  59009. this.INVERTNORMALMAPY = false;
  59010. this.SHADOWFULLFLOAT = false;
  59011. this.rebuild();
  59012. }
  59013. return PBRMaterialDefines;
  59014. })(BABYLON.MaterialDefines);
  59015. /**
  59016. * The Physically based material of BJS.
  59017. *
  59018. * This offers the main features of a standard PBR material.
  59019. * For more information, please refer to the documentation :
  59020. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  59021. */
  59022. var PBRMaterial = (function (_super) {
  59023. __extends(PBRMaterial, _super);
  59024. /**
  59025. * Instantiates a new PBRMaterial instance.
  59026. *
  59027. * @param name The material name
  59028. * @param scene The scene the material will be use in.
  59029. */
  59030. function PBRMaterial(name, scene) {
  59031. var _this = this;
  59032. _super.call(this, name, scene);
  59033. /**
  59034. * Intensity of the direct lights e.g. the four lights available in your scene.
  59035. * This impacts both the direct diffuse and specular highlights.
  59036. */
  59037. this.directIntensity = 1.0;
  59038. /**
  59039. * Intensity of the emissive part of the material.
  59040. * This helps controlling the emissive effect without modifying the emissive color.
  59041. */
  59042. this.emissiveIntensity = 1.0;
  59043. /**
  59044. * Intensity of the environment e.g. how much the environment will light the object
  59045. * either through harmonics for rough material or through the refelction for shiny ones.
  59046. */
  59047. this.environmentIntensity = 1.0;
  59048. /**
  59049. * This is a special control allowing the reduction of the specular highlights coming from the
  59050. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  59051. */
  59052. this.specularIntensity = 1.0;
  59053. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  59054. /**
  59055. * Debug Control allowing disabling the bump map on this material.
  59056. */
  59057. this.disableBumpMap = false;
  59058. /**
  59059. * Debug Control helping enforcing or dropping the darkness of shadows.
  59060. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  59061. */
  59062. this.overloadedShadowIntensity = 1.0;
  59063. /**
  59064. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  59065. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  59066. */
  59067. this.overloadedShadeIntensity = 1.0;
  59068. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  59069. /**
  59070. * The camera exposure used on this material.
  59071. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  59072. * This corresponds to a photographic exposure.
  59073. */
  59074. this.cameraExposure = 1.0;
  59075. /**
  59076. * The camera contrast used on this material.
  59077. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  59078. */
  59079. this.cameraContrast = 1.0;
  59080. /**
  59081. * Color Grading 2D Lookup Texture.
  59082. * This allows special effects like sepia, black and white to sixties rendering style.
  59083. */
  59084. this.cameraColorGradingTexture = null;
  59085. /**
  59086. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59087. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59088. * 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;
  59089. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59090. */
  59091. this.cameraColorCurves = null;
  59092. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  59093. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  59094. /**
  59095. * Debug Control allowing to overload the ambient color.
  59096. * This as to be use with the overloadedAmbientIntensity parameter.
  59097. */
  59098. this.overloadedAmbient = BABYLON.Color3.White();
  59099. /**
  59100. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  59101. */
  59102. this.overloadedAmbientIntensity = 0.0;
  59103. /**
  59104. * Debug Control allowing to overload the albedo color.
  59105. * This as to be use with the overloadedAlbedoIntensity parameter.
  59106. */
  59107. this.overloadedAlbedo = BABYLON.Color3.White();
  59108. /**
  59109. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  59110. */
  59111. this.overloadedAlbedoIntensity = 0.0;
  59112. /**
  59113. * Debug Control allowing to overload the reflectivity color.
  59114. * This as to be use with the overloadedReflectivityIntensity parameter.
  59115. */
  59116. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  59117. /**
  59118. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  59119. */
  59120. this.overloadedReflectivityIntensity = 0.0;
  59121. /**
  59122. * Debug Control allowing to overload the emissive color.
  59123. * This as to be use with the overloadedEmissiveIntensity parameter.
  59124. */
  59125. this.overloadedEmissive = BABYLON.Color3.White();
  59126. /**
  59127. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  59128. */
  59129. this.overloadedEmissiveIntensity = 0.0;
  59130. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  59131. /**
  59132. * Debug Control allowing to overload the reflection color.
  59133. * This as to be use with the overloadedReflectionIntensity parameter.
  59134. */
  59135. this.overloadedReflection = BABYLON.Color3.White();
  59136. /**
  59137. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  59138. */
  59139. this.overloadedReflectionIntensity = 0.0;
  59140. /**
  59141. * Debug Control allowing to overload the microsurface.
  59142. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  59143. */
  59144. this.overloadedMicroSurface = 0.0;
  59145. /**
  59146. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  59147. */
  59148. this.overloadedMicroSurfaceIntensity = 0.0;
  59149. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  59150. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  59151. /**
  59152. * AKA Diffuse Color in other nomenclature.
  59153. */
  59154. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  59155. /**
  59156. * AKA Specular Color in other nomenclature.
  59157. */
  59158. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  59159. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  59160. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  59161. /**
  59162. * AKA Glossiness in other nomenclature.
  59163. */
  59164. this.microSurface = 0.9;
  59165. /**
  59166. * source material index of refraction (IOR)' / 'destination material IOR.
  59167. */
  59168. this.indexOfRefraction = 0.66;
  59169. /**
  59170. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  59171. */
  59172. this.invertRefractionY = false;
  59173. /**
  59174. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  59175. * Materials half opaque for instance using refraction could benefit from this control.
  59176. */
  59177. this.linkRefractionWithTransparency = false;
  59178. /**
  59179. * The emissive and albedo are linked to never be more than one (Energy conservation).
  59180. */
  59181. this.linkEmissiveWithAlbedo = false;
  59182. this.useLightmapAsShadowmap = false;
  59183. /**
  59184. * In this mode, the emissive informtaion will always be added to the lighting once.
  59185. * A light for instance can be thought as emissive.
  59186. */
  59187. this.useEmissiveAsIllumination = false;
  59188. /**
  59189. * Secifies that the alpha is coming form the albedo channel alpha channel.
  59190. */
  59191. this.useAlphaFromAlbedoTexture = false;
  59192. /**
  59193. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  59194. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  59195. */
  59196. this.useSpecularOverAlpha = true;
  59197. /**
  59198. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  59199. */
  59200. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  59201. /**
  59202. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  59203. * The material will try to infer what glossiness each pixel should be.
  59204. */
  59205. this.useAutoMicroSurfaceFromReflectivityMap = false;
  59206. /**
  59207. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  59208. * the creation of the material.
  59209. */
  59210. this.useScalarInLinearSpace = false;
  59211. /**
  59212. * BJS is using an harcoded light falloff based on a manually sets up range.
  59213. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  59214. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  59215. */
  59216. this.usePhysicalLightFalloff = true;
  59217. /**
  59218. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  59219. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  59220. */
  59221. this.useRadianceOverAlpha = true;
  59222. /**
  59223. * Allows using the bump map in parallax mode.
  59224. */
  59225. this.useParallax = false;
  59226. /**
  59227. * Allows using the bump map in parallax occlusion mode.
  59228. */
  59229. this.useParallaxOcclusion = false;
  59230. /**
  59231. * Controls the scale bias of the parallax mode.
  59232. */
  59233. this.parallaxScaleBias = 0.05;
  59234. /**
  59235. * If sets to true, disables all the lights affecting the material.
  59236. */
  59237. this.disableLighting = false;
  59238. /**
  59239. * Number of Simultaneous lights allowed on the material.
  59240. */
  59241. this.maxSimultaneousLights = 4;
  59242. /**
  59243. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  59244. */
  59245. this.invertNormalMapX = false;
  59246. /**
  59247. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  59248. */
  59249. this.invertNormalMapY = false;
  59250. this._renderTargets = new BABYLON.SmartArray(16);
  59251. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  59252. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  59253. this._tempColor = new BABYLON.Color3();
  59254. this._defines = new PBRMaterialDefines();
  59255. this._cachedDefines = new PBRMaterialDefines();
  59256. this._myScene = null;
  59257. this._myShadowGenerator = null;
  59258. this._cachedDefines.BonesPerMesh = -1;
  59259. this.getRenderTargetTextures = function () {
  59260. _this._renderTargets.reset();
  59261. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  59262. _this._renderTargets.push(_this.reflectionTexture);
  59263. }
  59264. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  59265. _this._renderTargets.push(_this.refractionTexture);
  59266. }
  59267. return _this._renderTargets;
  59268. };
  59269. }
  59270. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  59271. get: function () {
  59272. return this._useLogarithmicDepth;
  59273. },
  59274. set: function (value) {
  59275. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  59276. },
  59277. enumerable: true,
  59278. configurable: true
  59279. });
  59280. PBRMaterial.prototype.needAlphaBlending = function () {
  59281. if (this.linkRefractionWithTransparency) {
  59282. return false;
  59283. }
  59284. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  59285. };
  59286. PBRMaterial.prototype.needAlphaTesting = function () {
  59287. if (this.linkRefractionWithTransparency) {
  59288. return false;
  59289. }
  59290. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  59291. };
  59292. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  59293. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  59294. };
  59295. PBRMaterial.prototype.getAlphaTestTexture = function () {
  59296. return this.albedoTexture;
  59297. };
  59298. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59299. if (!mesh) {
  59300. return true;
  59301. }
  59302. if (this._defines.INSTANCES !== useInstances) {
  59303. return false;
  59304. }
  59305. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  59306. return true;
  59307. }
  59308. return false;
  59309. };
  59310. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  59311. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  59312. };
  59313. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  59314. if (!useScalarInLinear) {
  59315. color.toLinearSpaceToRef(ref);
  59316. }
  59317. else {
  59318. ref.r = color.r;
  59319. ref.g = color.g;
  59320. ref.b = color.b;
  59321. }
  59322. };
  59323. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  59324. var lightIndex = 0;
  59325. var depthValuesAlreadySet = false;
  59326. for (var index = 0; index < scene.lights.length; index++) {
  59327. var light = scene.lights[index];
  59328. if (!light.isEnabled()) {
  59329. continue;
  59330. }
  59331. if (!light.canAffectMesh(mesh)) {
  59332. continue;
  59333. }
  59334. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  59335. // GAMMA CORRECTION.
  59336. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  59337. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  59338. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  59339. if (defines["SPECULARTERM"]) {
  59340. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  59341. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  59342. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  59343. }
  59344. // Shadows
  59345. if (scene.shadowsEnabled) {
  59346. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  59347. }
  59348. lightIndex++;
  59349. if (lightIndex === maxSimultaneousLights)
  59350. break;
  59351. }
  59352. };
  59353. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  59354. if (this.checkReadyOnlyOnce) {
  59355. if (this._wasPreviouslyReady) {
  59356. return true;
  59357. }
  59358. }
  59359. var scene = this.getScene();
  59360. if (!this.checkReadyOnEveryCall) {
  59361. if (this._renderId === scene.getRenderId()) {
  59362. if (this._checkCache(scene, mesh, useInstances)) {
  59363. return true;
  59364. }
  59365. }
  59366. }
  59367. var engine = scene.getEngine();
  59368. var needNormals = false;
  59369. var needUVs = false;
  59370. this._defines.reset();
  59371. if (scene.texturesEnabled) {
  59372. // Textures
  59373. if (scene.texturesEnabled) {
  59374. if (scene.getEngine().getCaps().textureLOD) {
  59375. this._defines.LODBASEDMICROSFURACE = true;
  59376. }
  59377. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59378. if (!this.albedoTexture.isReady()) {
  59379. return false;
  59380. }
  59381. else {
  59382. needUVs = true;
  59383. this._defines.ALBEDO = true;
  59384. }
  59385. }
  59386. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59387. if (!this.ambientTexture.isReady()) {
  59388. return false;
  59389. }
  59390. else {
  59391. needUVs = true;
  59392. this._defines.AMBIENT = true;
  59393. }
  59394. }
  59395. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59396. if (!this.opacityTexture.isReady()) {
  59397. return false;
  59398. }
  59399. else {
  59400. needUVs = true;
  59401. this._defines.OPACITY = true;
  59402. if (this.opacityTexture.getAlphaFromRGB) {
  59403. this._defines.OPACITYRGB = true;
  59404. }
  59405. }
  59406. }
  59407. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59408. if (!this.reflectionTexture.isReady()) {
  59409. return false;
  59410. }
  59411. else {
  59412. needNormals = true;
  59413. this._defines.REFLECTION = true;
  59414. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  59415. this._defines.INVERTCUBICMAP = true;
  59416. }
  59417. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  59418. switch (this.reflectionTexture.coordinatesMode) {
  59419. case BABYLON.Texture.CUBIC_MODE:
  59420. case BABYLON.Texture.INVCUBIC_MODE:
  59421. this._defines.REFLECTIONMAP_CUBIC = true;
  59422. break;
  59423. case BABYLON.Texture.EXPLICIT_MODE:
  59424. this._defines.REFLECTIONMAP_EXPLICIT = true;
  59425. break;
  59426. case BABYLON.Texture.PLANAR_MODE:
  59427. this._defines.REFLECTIONMAP_PLANAR = true;
  59428. break;
  59429. case BABYLON.Texture.PROJECTION_MODE:
  59430. this._defines.REFLECTIONMAP_PROJECTION = true;
  59431. break;
  59432. case BABYLON.Texture.SKYBOX_MODE:
  59433. this._defines.REFLECTIONMAP_SKYBOX = true;
  59434. break;
  59435. case BABYLON.Texture.SPHERICAL_MODE:
  59436. this._defines.REFLECTIONMAP_SPHERICAL = true;
  59437. break;
  59438. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  59439. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  59440. break;
  59441. }
  59442. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  59443. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  59444. needNormals = true;
  59445. if (this.reflectionTexture.isPMREM) {
  59446. this._defines.USEPMREMREFLECTION = true;
  59447. }
  59448. }
  59449. }
  59450. }
  59451. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59452. if (!this.lightmapTexture.isReady()) {
  59453. return false;
  59454. }
  59455. else {
  59456. needUVs = true;
  59457. this._defines.LIGHTMAP = true;
  59458. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  59459. }
  59460. }
  59461. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59462. if (!this.emissiveTexture.isReady()) {
  59463. return false;
  59464. }
  59465. else {
  59466. needUVs = true;
  59467. this._defines.EMISSIVE = true;
  59468. }
  59469. }
  59470. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59471. if (!this.reflectivityTexture.isReady()) {
  59472. return false;
  59473. }
  59474. else {
  59475. needUVs = true;
  59476. this._defines.REFLECTIVITY = true;
  59477. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  59478. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  59479. }
  59480. }
  59481. }
  59482. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59483. if (!this.bumpTexture.isReady()) {
  59484. return false;
  59485. }
  59486. else {
  59487. needUVs = true;
  59488. this._defines.BUMP = true;
  59489. if (this.useParallax) {
  59490. this._defines.PARALLAX = true;
  59491. if (this.useParallaxOcclusion) {
  59492. this._defines.PARALLAXOCCLUSION = true;
  59493. }
  59494. }
  59495. if (this.invertNormalMapX) {
  59496. this._defines.INVERTNORMALMAPX = true;
  59497. }
  59498. if (this.invertNormalMapY) {
  59499. this._defines.INVERTNORMALMAPY = true;
  59500. }
  59501. }
  59502. }
  59503. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59504. if (!this.refractionTexture.isReady()) {
  59505. return false;
  59506. }
  59507. else {
  59508. needUVs = true;
  59509. this._defines.REFRACTION = true;
  59510. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  59511. if (this.linkRefractionWithTransparency) {
  59512. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  59513. }
  59514. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  59515. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  59516. if (this.refractionTexture.isPMREM) {
  59517. this._defines.USEPMREMREFRACTION = true;
  59518. }
  59519. }
  59520. }
  59521. }
  59522. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59523. if (!this.cameraColorGradingTexture.isReady()) {
  59524. return false;
  59525. }
  59526. else {
  59527. this._defines.CAMERACOLORGRADING = true;
  59528. }
  59529. }
  59530. }
  59531. // Effect
  59532. if (scene.clipPlane) {
  59533. this._defines.CLIPPLANE = true;
  59534. }
  59535. if (engine.getAlphaTesting()) {
  59536. this._defines.ALPHATEST = true;
  59537. }
  59538. if (this._shouldUseAlphaFromAlbedoTexture()) {
  59539. this._defines.ALPHAFROMALBEDO = true;
  59540. }
  59541. if (this.useEmissiveAsIllumination) {
  59542. this._defines.EMISSIVEASILLUMINATION = true;
  59543. }
  59544. if (this.linkEmissiveWithAlbedo) {
  59545. this._defines.LINKEMISSIVEWITHALBEDO = true;
  59546. }
  59547. if (this.useLogarithmicDepth) {
  59548. this._defines.LOGARITHMICDEPTH = true;
  59549. }
  59550. if (this.cameraContrast != 1) {
  59551. this._defines.CAMERACONTRAST = true;
  59552. }
  59553. if (this.cameraExposure != 1) {
  59554. this._defines.CAMERATONEMAP = true;
  59555. }
  59556. if (this.cameraColorCurves) {
  59557. this._defines.CAMERACOLORCURVES = true;
  59558. }
  59559. if (this.overloadedShadeIntensity != 1 ||
  59560. this.overloadedShadowIntensity != 1) {
  59561. this._defines.OVERLOADEDSHADOWVALUES = true;
  59562. }
  59563. if (this.overloadedMicroSurfaceIntensity > 0 ||
  59564. this.overloadedEmissiveIntensity > 0 ||
  59565. this.overloadedReflectivityIntensity > 0 ||
  59566. this.overloadedAlbedoIntensity > 0 ||
  59567. this.overloadedAmbientIntensity > 0 ||
  59568. this.overloadedReflectionIntensity > 0) {
  59569. this._defines.OVERLOADEDVALUES = true;
  59570. }
  59571. // Point size
  59572. if (this.pointsCloud || scene.forcePointsCloud) {
  59573. this._defines.POINTSIZE = true;
  59574. }
  59575. // Fog
  59576. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  59577. this._defines.FOG = true;
  59578. }
  59579. if (scene.lightsEnabled && !this.disableLighting) {
  59580. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  59581. }
  59582. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59583. // Fresnel
  59584. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  59585. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59586. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59587. this._defines.OPACITYFRESNEL = true;
  59588. }
  59589. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59590. this._defines.EMISSIVEFRESNEL = true;
  59591. }
  59592. needNormals = true;
  59593. this._defines.FRESNEL = true;
  59594. }
  59595. }
  59596. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  59597. this._defines.SPECULAROVERALPHA = true;
  59598. }
  59599. if (this.usePhysicalLightFalloff) {
  59600. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  59601. }
  59602. if (this.useRadianceOverAlpha) {
  59603. this._defines.RADIANCEOVERALPHA = true;
  59604. }
  59605. // Attribs
  59606. if (mesh) {
  59607. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  59608. this._defines.NORMAL = true;
  59609. }
  59610. if (needUVs) {
  59611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59612. this._defines.UV1 = true;
  59613. }
  59614. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59615. this._defines.UV2 = true;
  59616. }
  59617. }
  59618. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59619. this._defines.VERTEXCOLOR = true;
  59620. if (mesh.hasVertexAlpha) {
  59621. this._defines.VERTEXALPHA = true;
  59622. }
  59623. }
  59624. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59625. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  59626. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  59627. }
  59628. // Instances
  59629. if (useInstances) {
  59630. this._defines.INSTANCES = true;
  59631. }
  59632. }
  59633. // Get correct effect
  59634. if (!this._defines.isEqual(this._cachedDefines)) {
  59635. this._defines.cloneTo(this._cachedDefines);
  59636. scene.resetCachedMaterial();
  59637. // Fallbacks
  59638. var fallbacks = new BABYLON.EffectFallbacks();
  59639. if (this._defines.REFLECTION) {
  59640. fallbacks.addFallback(0, "REFLECTION");
  59641. }
  59642. if (this._defines.REFRACTION) {
  59643. fallbacks.addFallback(0, "REFRACTION");
  59644. }
  59645. if (this._defines.REFLECTIVITY) {
  59646. fallbacks.addFallback(0, "REFLECTIVITY");
  59647. }
  59648. if (this._defines.BUMP) {
  59649. fallbacks.addFallback(0, "BUMP");
  59650. }
  59651. if (this._defines.PARALLAX) {
  59652. fallbacks.addFallback(1, "PARALLAX");
  59653. }
  59654. if (this._defines.PARALLAXOCCLUSION) {
  59655. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  59656. }
  59657. if (this._defines.SPECULAROVERALPHA) {
  59658. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  59659. }
  59660. if (this._defines.FOG) {
  59661. fallbacks.addFallback(1, "FOG");
  59662. }
  59663. if (this._defines.POINTSIZE) {
  59664. fallbacks.addFallback(0, "POINTSIZE");
  59665. }
  59666. if (this._defines.LOGARITHMICDEPTH) {
  59667. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  59668. }
  59669. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  59670. if (this._defines.SPECULARTERM) {
  59671. fallbacks.addFallback(0, "SPECULARTERM");
  59672. }
  59673. if (this._defines.OPACITYFRESNEL) {
  59674. fallbacks.addFallback(1, "OPACITYFRESNEL");
  59675. }
  59676. if (this._defines.EMISSIVEFRESNEL) {
  59677. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  59678. }
  59679. if (this._defines.FRESNEL) {
  59680. fallbacks.addFallback(3, "FRESNEL");
  59681. }
  59682. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  59683. fallbacks.addCPUSkinningFallback(0, mesh);
  59684. }
  59685. //Attributes
  59686. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59687. if (this._defines.NORMAL) {
  59688. attribs.push(BABYLON.VertexBuffer.NormalKind);
  59689. }
  59690. if (this._defines.UV1) {
  59691. attribs.push(BABYLON.VertexBuffer.UVKind);
  59692. }
  59693. if (this._defines.UV2) {
  59694. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59695. }
  59696. if (this._defines.VERTEXCOLOR) {
  59697. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59698. }
  59699. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  59700. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  59701. // Legacy browser patch
  59702. var shaderName = "pbr";
  59703. if (!scene.getEngine().getCaps().standardDerivatives) {
  59704. shaderName = "legacypbr";
  59705. }
  59706. var join = this._defines.toString();
  59707. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  59708. "vFogInfos", "vFogColor", "pointSize",
  59709. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  59710. "mBones",
  59711. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  59712. "depthValues",
  59713. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  59714. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  59715. "logarithmicDepthConstant",
  59716. "vSphericalX", "vSphericalY", "vSphericalZ",
  59717. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  59718. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  59719. "vMicrosurfaceTextureLods",
  59720. "vCameraInfos"
  59721. ];
  59722. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  59723. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  59724. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  59725. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  59726. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  59727. }
  59728. if (!this._effect.isReady()) {
  59729. return false;
  59730. }
  59731. this._renderId = scene.getRenderId();
  59732. this._wasPreviouslyReady = true;
  59733. if (mesh) {
  59734. if (!mesh._materialDefines) {
  59735. mesh._materialDefines = new PBRMaterialDefines();
  59736. }
  59737. this._defines.cloneTo(mesh._materialDefines);
  59738. }
  59739. return true;
  59740. };
  59741. PBRMaterial.prototype.unbind = function () {
  59742. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  59743. this._effect.setTexture("reflection2DSampler", null);
  59744. }
  59745. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  59746. this._effect.setTexture("refraction2DSampler", null);
  59747. }
  59748. _super.prototype.unbind.call(this);
  59749. };
  59750. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59751. this._effect.setMatrix("world", world);
  59752. };
  59753. PBRMaterial.prototype.bind = function (world, mesh) {
  59754. this._myScene = this.getScene();
  59755. // Matrices
  59756. this.bindOnlyWorldMatrix(world);
  59757. // Bones
  59758. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59759. if (this._myScene.getCachedMaterial() !== this) {
  59760. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  59761. if (BABYLON.StandardMaterial.FresnelEnabled) {
  59762. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  59763. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  59764. }
  59765. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  59766. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  59767. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  59768. }
  59769. }
  59770. // Textures
  59771. if (this._myScene.texturesEnabled) {
  59772. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  59773. this._effect.setTexture("albedoSampler", this.albedoTexture);
  59774. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  59775. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  59776. }
  59777. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  59778. this._effect.setTexture("ambientSampler", this.ambientTexture);
  59779. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  59780. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  59781. }
  59782. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  59783. this._effect.setTexture("opacitySampler", this.opacityTexture);
  59784. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  59785. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  59786. }
  59787. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  59788. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  59789. if (this.reflectionTexture.isCube) {
  59790. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  59791. }
  59792. else {
  59793. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  59794. }
  59795. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  59796. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  59797. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  59798. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  59799. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  59800. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  59801. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  59802. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  59803. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  59804. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  59805. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  59806. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  59807. }
  59808. }
  59809. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  59810. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  59811. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  59812. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  59813. }
  59814. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  59815. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  59816. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  59817. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  59818. }
  59819. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  59820. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  59821. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  59822. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  59823. }
  59824. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  59825. this._effect.setTexture("bumpSampler", this.bumpTexture);
  59826. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  59827. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  59828. }
  59829. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  59830. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  59831. var depth = 1.0;
  59832. if (this.refractionTexture.isCube) {
  59833. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  59834. }
  59835. else {
  59836. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  59837. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  59838. if (this.refractionTexture.depth) {
  59839. depth = this.refractionTexture.depth;
  59840. }
  59841. }
  59842. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  59843. }
  59844. if ((this.reflectionTexture || this.refractionTexture)) {
  59845. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  59846. }
  59847. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  59848. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  59849. }
  59850. }
  59851. // Clip plane
  59852. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  59853. // Point size
  59854. if (this.pointsCloud) {
  59855. this._effect.setFloat("pointSize", this.pointSize);
  59856. }
  59857. // Colors
  59858. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  59859. // GAMMA CORRECTION.
  59860. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  59861. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  59862. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  59863. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  59864. // GAMMA CORRECTION.
  59865. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  59866. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  59867. // GAMMA CORRECTION.
  59868. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  59869. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  59870. }
  59871. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  59872. // GAMMA CORRECTION.
  59873. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  59874. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  59875. // Lights
  59876. if (this._myScene.lightsEnabled && !this.disableLighting) {
  59877. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  59878. }
  59879. // View
  59880. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  59881. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  59882. }
  59883. // Fog
  59884. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  59885. this._lightingInfos.x = this.directIntensity;
  59886. this._lightingInfos.y = this.emissiveIntensity;
  59887. this._lightingInfos.z = this.environmentIntensity;
  59888. this._lightingInfos.w = this.specularIntensity;
  59889. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  59890. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  59891. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  59892. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  59893. this._cameraInfos.x = this.cameraExposure;
  59894. this._cameraInfos.y = this.cameraContrast;
  59895. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  59896. if (this.cameraColorCurves) {
  59897. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  59898. }
  59899. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  59900. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  59901. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  59902. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  59903. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  59904. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  59905. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  59906. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  59907. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  59908. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  59909. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  59910. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  59911. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  59912. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  59913. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  59914. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  59915. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  59916. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  59917. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  59918. // Log. depth
  59919. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  59920. }
  59921. _super.prototype.bind.call(this, world, mesh);
  59922. this._myScene = null;
  59923. };
  59924. PBRMaterial.prototype.getAnimatables = function () {
  59925. var results = [];
  59926. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  59927. results.push(this.albedoTexture);
  59928. }
  59929. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  59930. results.push(this.ambientTexture);
  59931. }
  59932. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  59933. results.push(this.opacityTexture);
  59934. }
  59935. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  59936. results.push(this.reflectionTexture);
  59937. }
  59938. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  59939. results.push(this.emissiveTexture);
  59940. }
  59941. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  59942. results.push(this.reflectivityTexture);
  59943. }
  59944. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  59945. results.push(this.bumpTexture);
  59946. }
  59947. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  59948. results.push(this.lightmapTexture);
  59949. }
  59950. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  59951. results.push(this.refractionTexture);
  59952. }
  59953. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59954. results.push(this.cameraColorGradingTexture);
  59955. }
  59956. return results;
  59957. };
  59958. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59959. if (forceDisposeTextures) {
  59960. if (this.albedoTexture) {
  59961. this.albedoTexture.dispose();
  59962. }
  59963. if (this.ambientTexture) {
  59964. this.ambientTexture.dispose();
  59965. }
  59966. if (this.opacityTexture) {
  59967. this.opacityTexture.dispose();
  59968. }
  59969. if (this.reflectionTexture) {
  59970. this.reflectionTexture.dispose();
  59971. }
  59972. if (this.emissiveTexture) {
  59973. this.emissiveTexture.dispose();
  59974. }
  59975. if (this.reflectivityTexture) {
  59976. this.reflectivityTexture.dispose();
  59977. }
  59978. if (this.bumpTexture) {
  59979. this.bumpTexture.dispose();
  59980. }
  59981. if (this.lightmapTexture) {
  59982. this.lightmapTexture.dispose();
  59983. }
  59984. if (this.refractionTexture) {
  59985. this.refractionTexture.dispose();
  59986. }
  59987. if (this.cameraColorGradingTexture) {
  59988. this.cameraColorGradingTexture.dispose();
  59989. }
  59990. }
  59991. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59992. };
  59993. PBRMaterial.prototype.clone = function (name) {
  59994. var _this = this;
  59995. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59996. };
  59997. PBRMaterial.prototype.serialize = function () {
  59998. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59999. serializationObject.customType = "BABYLON.PBRMaterial";
  60000. return serializationObject;
  60001. };
  60002. // Statics
  60003. PBRMaterial.Parse = function (source, scene, rootUrl) {
  60004. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  60005. };
  60006. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  60007. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  60008. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  60009. PBRMaterial._scaledReflection = new BABYLON.Color3();
  60010. __decorate([
  60011. BABYLON.serialize()
  60012. ], PBRMaterial.prototype, "directIntensity", void 0);
  60013. __decorate([
  60014. BABYLON.serialize()
  60015. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  60016. __decorate([
  60017. BABYLON.serialize()
  60018. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  60019. __decorate([
  60020. BABYLON.serialize()
  60021. ], PBRMaterial.prototype, "specularIntensity", void 0);
  60022. __decorate([
  60023. BABYLON.serialize()
  60024. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  60025. __decorate([
  60026. BABYLON.serialize()
  60027. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  60028. __decorate([
  60029. BABYLON.serialize()
  60030. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  60031. __decorate([
  60032. BABYLON.serialize()
  60033. ], PBRMaterial.prototype, "cameraExposure", void 0);
  60034. __decorate([
  60035. BABYLON.serialize()
  60036. ], PBRMaterial.prototype, "cameraContrast", void 0);
  60037. __decorate([
  60038. BABYLON.serializeAsTexture()
  60039. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  60040. __decorate([
  60041. BABYLON.serializeAsColorCurves()
  60042. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  60043. __decorate([
  60044. BABYLON.serializeAsColor3()
  60045. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  60046. __decorate([
  60047. BABYLON.serialize()
  60048. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  60049. __decorate([
  60050. BABYLON.serializeAsColor3()
  60051. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  60052. __decorate([
  60053. BABYLON.serialize()
  60054. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  60055. __decorate([
  60056. BABYLON.serializeAsColor3()
  60057. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  60058. __decorate([
  60059. BABYLON.serialize()
  60060. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  60061. __decorate([
  60062. BABYLON.serializeAsColor3()
  60063. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  60064. __decorate([
  60065. BABYLON.serialize()
  60066. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  60067. __decorate([
  60068. BABYLON.serializeAsColor3()
  60069. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  60070. __decorate([
  60071. BABYLON.serialize()
  60072. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  60073. __decorate([
  60074. BABYLON.serialize()
  60075. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  60076. __decorate([
  60077. BABYLON.serialize()
  60078. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  60079. __decorate([
  60080. BABYLON.serializeAsTexture()
  60081. ], PBRMaterial.prototype, "albedoTexture", void 0);
  60082. __decorate([
  60083. BABYLON.serializeAsTexture()
  60084. ], PBRMaterial.prototype, "ambientTexture", void 0);
  60085. __decorate([
  60086. BABYLON.serializeAsTexture()
  60087. ], PBRMaterial.prototype, "opacityTexture", void 0);
  60088. __decorate([
  60089. BABYLON.serializeAsTexture()
  60090. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  60091. __decorate([
  60092. BABYLON.serializeAsTexture()
  60093. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  60094. __decorate([
  60095. BABYLON.serializeAsTexture()
  60096. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  60097. __decorate([
  60098. BABYLON.serializeAsTexture()
  60099. ], PBRMaterial.prototype, "bumpTexture", void 0);
  60100. __decorate([
  60101. BABYLON.serializeAsTexture()
  60102. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  60103. __decorate([
  60104. BABYLON.serializeAsTexture()
  60105. ], PBRMaterial.prototype, "refractionTexture", void 0);
  60106. __decorate([
  60107. BABYLON.serializeAsColor3("ambient")
  60108. ], PBRMaterial.prototype, "ambientColor", void 0);
  60109. __decorate([
  60110. BABYLON.serializeAsColor3("albedo")
  60111. ], PBRMaterial.prototype, "albedoColor", void 0);
  60112. __decorate([
  60113. BABYLON.serializeAsColor3("reflectivity")
  60114. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  60115. __decorate([
  60116. BABYLON.serializeAsColor3("reflection")
  60117. ], PBRMaterial.prototype, "reflectionColor", void 0);
  60118. __decorate([
  60119. BABYLON.serializeAsColor3("emissive")
  60120. ], PBRMaterial.prototype, "emissiveColor", void 0);
  60121. __decorate([
  60122. BABYLON.serialize()
  60123. ], PBRMaterial.prototype, "microSurface", void 0);
  60124. __decorate([
  60125. BABYLON.serialize()
  60126. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  60127. __decorate([
  60128. BABYLON.serialize()
  60129. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  60130. __decorate([
  60131. BABYLON.serializeAsFresnelParameters()
  60132. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  60133. __decorate([
  60134. BABYLON.serializeAsFresnelParameters()
  60135. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  60136. __decorate([
  60137. BABYLON.serialize()
  60138. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  60139. __decorate([
  60140. BABYLON.serialize()
  60141. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  60142. __decorate([
  60143. BABYLON.serialize()
  60144. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  60145. __decorate([
  60146. BABYLON.serialize()
  60147. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  60148. __decorate([
  60149. BABYLON.serialize()
  60150. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  60151. __decorate([
  60152. BABYLON.serialize()
  60153. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  60154. __decorate([
  60155. BABYLON.serialize()
  60156. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  60157. __decorate([
  60158. BABYLON.serialize()
  60159. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  60160. __decorate([
  60161. BABYLON.serialize()
  60162. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  60163. __decorate([
  60164. BABYLON.serialize()
  60165. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  60166. __decorate([
  60167. BABYLON.serialize()
  60168. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  60169. __decorate([
  60170. BABYLON.serialize()
  60171. ], PBRMaterial.prototype, "useParallax", void 0);
  60172. __decorate([
  60173. BABYLON.serialize()
  60174. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  60175. __decorate([
  60176. BABYLON.serialize()
  60177. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  60178. __decorate([
  60179. BABYLON.serialize()
  60180. ], PBRMaterial.prototype, "disableLighting", void 0);
  60181. __decorate([
  60182. BABYLON.serialize()
  60183. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  60184. __decorate([
  60185. BABYLON.serialize()
  60186. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  60187. __decorate([
  60188. BABYLON.serialize()
  60189. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  60190. __decorate([
  60191. BABYLON.serialize()
  60192. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  60193. return PBRMaterial;
  60194. })(BABYLON.Material);
  60195. BABYLON.PBRMaterial = PBRMaterial;
  60196. })(BABYLON || (BABYLON = {}));
  60197. var BABYLON;
  60198. (function (BABYLON) {
  60199. var DebugLayer = (function () {
  60200. function DebugLayer(scene) {
  60201. var _this = this;
  60202. this._transformationMatrix = BABYLON.Matrix.Identity();
  60203. this._enabled = false;
  60204. this._labelsEnabled = false;
  60205. this._displayStatistics = true;
  60206. this._displayTree = false;
  60207. this._displayLogs = false;
  60208. this._skeletonViewers = new Array();
  60209. this._identityMatrix = BABYLON.Matrix.Identity();
  60210. this.axisRatio = 0.02;
  60211. this.accentColor = "orange";
  60212. this._scene = scene;
  60213. this._syncPositions = function () {
  60214. var engine = _this._scene.getEngine();
  60215. var canvasRect = engine.getRenderingCanvasClientRect();
  60216. if (_this._showUI) {
  60217. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  60218. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  60219. _this._statsDiv.style.width = "400px";
  60220. _this._statsDiv.style.height = "auto";
  60221. _this._statsSubsetDiv.style.maxHeight = "240px";
  60222. _this._optionsDiv.style.left = "0px";
  60223. _this._optionsDiv.style.top = "10px";
  60224. _this._optionsDiv.style.width = "200px";
  60225. _this._optionsDiv.style.height = "auto";
  60226. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  60227. _this._logDiv.style.left = "0px";
  60228. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  60229. _this._logDiv.style.width = "600px";
  60230. _this._logDiv.style.height = "160px";
  60231. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  60232. _this._treeDiv.style.top = "10px";
  60233. _this._treeDiv.style.width = "300px";
  60234. _this._treeDiv.style.height = "auto";
  60235. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  60236. }
  60237. _this._globalDiv.style.left = canvasRect.left + "px";
  60238. _this._globalDiv.style.top = canvasRect.top + "px";
  60239. _this._drawingCanvas.style.left = "0px";
  60240. _this._drawingCanvas.style.top = "0px";
  60241. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  60242. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  60243. var devicePixelRatio = window.devicePixelRatio || 1;
  60244. var context = _this._drawingContext;
  60245. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  60246. context.mozBackingStorePixelRatio ||
  60247. context.msBackingStorePixelRatio ||
  60248. context.oBackingStorePixelRatio ||
  60249. context.backingStorePixelRatio || 1;
  60250. _this._ratio = devicePixelRatio / backingStoreRatio;
  60251. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  60252. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  60253. };
  60254. this._onCanvasClick = function (evt) {
  60255. _this._clickPosition = {
  60256. x: evt.clientX * _this._ratio,
  60257. y: evt.clientY * _this._ratio
  60258. };
  60259. };
  60260. this._syncUI = function () {
  60261. if (_this._showUI) {
  60262. if (_this._displayStatistics) {
  60263. _this._displayStats();
  60264. _this._statsDiv.style.display = "";
  60265. }
  60266. else {
  60267. _this._statsDiv.style.display = "none";
  60268. }
  60269. if (_this._displayLogs) {
  60270. _this._logDiv.style.display = "";
  60271. }
  60272. else {
  60273. _this._logDiv.style.display = "none";
  60274. }
  60275. if (_this._displayTree) {
  60276. _this._treeDiv.style.display = "";
  60277. if (_this._needToRefreshMeshesTree) {
  60278. _this._needToRefreshMeshesTree = false;
  60279. _this._refreshMeshesTreeContent();
  60280. }
  60281. }
  60282. else {
  60283. _this._treeDiv.style.display = "none";
  60284. }
  60285. }
  60286. };
  60287. this._syncData = function () {
  60288. if (_this._labelsEnabled || !_this._showUI) {
  60289. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  60290. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  60291. var engine = _this._scene.getEngine();
  60292. var viewport = _this._camera.viewport;
  60293. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60294. // Meshes
  60295. var meshes = _this._camera.getActiveMeshes();
  60296. var index;
  60297. var projectedPosition;
  60298. for (index = 0; index < meshes.length; index++) {
  60299. var mesh = meshes.data[index];
  60300. var position = mesh.getBoundingInfo().boundingSphere.center;
  60301. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  60302. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  60303. _this._renderAxis(projectedPosition, mesh, globalViewport);
  60304. }
  60305. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  60306. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  60307. }
  60308. }
  60309. // Cameras
  60310. var cameras = _this._scene.cameras;
  60311. for (index = 0; index < cameras.length; index++) {
  60312. var camera = cameras[index];
  60313. if (camera === _this._camera) {
  60314. continue;
  60315. }
  60316. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  60317. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  60318. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  60319. _this._camera.detachControl(engine.getRenderingCanvas());
  60320. _this._camera = camera;
  60321. _this._camera.attachControl(engine.getRenderingCanvas());
  60322. }, function () { return "purple"; });
  60323. }
  60324. }
  60325. // Lights
  60326. var lights = _this._scene.lights;
  60327. for (index = 0; index < lights.length; index++) {
  60328. var light = lights[index];
  60329. if (light.position) {
  60330. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  60331. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  60332. _this._renderLabel(light.name, projectedPosition, -20, function () {
  60333. light.setEnabled(!light.isEnabled());
  60334. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  60335. }
  60336. }
  60337. }
  60338. }
  60339. _this._clickPosition = undefined;
  60340. };
  60341. }
  60342. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  60343. while (this._treeSubsetDiv.hasChildNodes()) {
  60344. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  60345. }
  60346. // Add meshes
  60347. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  60348. sortedArray.sort(function (a, b) {
  60349. if (a.name === b.name) {
  60350. return 0;
  60351. }
  60352. return (a.name > b.name) ? 1 : -1;
  60353. });
  60354. for (var index = 0; index < sortedArray.length; index++) {
  60355. var mesh = sortedArray[index];
  60356. if (!mesh.isEnabled()) {
  60357. continue;
  60358. }
  60359. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  60360. m.isVisible = element.checked;
  60361. }, mesh);
  60362. }
  60363. };
  60364. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  60365. this._drawingContext.beginPath();
  60366. this._drawingContext.moveTo(zero.x, zero.y);
  60367. this._drawingContext.lineTo(unit.x, unit.y);
  60368. this._drawingContext.strokeStyle = color;
  60369. this._drawingContext.lineWidth = 4;
  60370. this._drawingContext.stroke();
  60371. this._drawingContext.font = "normal 14px Segoe UI";
  60372. this._drawingContext.fillStyle = color;
  60373. this._drawingContext.fillText(label, unitText.x, unitText.y);
  60374. };
  60375. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  60376. var position = mesh.getBoundingInfo().boundingSphere.center;
  60377. var worldMatrix = mesh.getWorldMatrix();
  60378. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  60379. var unit = (unprojectedVector.subtract(position)).length();
  60380. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60381. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60382. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  60383. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60384. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  60385. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  60386. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  60387. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  60388. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  60389. };
  60390. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  60391. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  60392. this._drawingContext.font = "normal 12px Segoe UI";
  60393. var textMetrics = this._drawingContext.measureText(text);
  60394. var centerX = projectedPosition.x - textMetrics.width / 2;
  60395. var centerY = projectedPosition.y;
  60396. var clientRect = this._drawingCanvas.getBoundingClientRect();
  60397. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  60398. onClick();
  60399. }
  60400. this._drawingContext.beginPath();
  60401. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  60402. this._drawingContext.fillStyle = getFillStyle();
  60403. this._drawingContext.globalAlpha = 0.5;
  60404. this._drawingContext.fill();
  60405. this._drawingContext.globalAlpha = 1.0;
  60406. this._drawingContext.strokeStyle = '#FFFFFF';
  60407. this._drawingContext.lineWidth = 1;
  60408. this._drawingContext.stroke();
  60409. this._drawingContext.fillStyle = "#FFFFFF";
  60410. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  60411. this._drawingContext.beginPath();
  60412. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  60413. this._drawingContext.fill();
  60414. }
  60415. };
  60416. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  60417. if (!this._clickPosition) {
  60418. return false;
  60419. }
  60420. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  60421. return false;
  60422. }
  60423. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  60424. return false;
  60425. }
  60426. return true;
  60427. };
  60428. DebugLayer.prototype.isVisible = function () {
  60429. return this._enabled;
  60430. };
  60431. DebugLayer.prototype.hide = function () {
  60432. if (!this._enabled) {
  60433. return;
  60434. }
  60435. this._enabled = false;
  60436. var engine = this._scene.getEngine();
  60437. this._scene.unregisterBeforeRender(this._syncData);
  60438. this._scene.unregisterAfterRender(this._syncUI);
  60439. this._rootElement.removeChild(this._globalDiv);
  60440. this._scene.forceShowBoundingBoxes = false;
  60441. this._scene.forceWireframe = false;
  60442. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  60443. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  60444. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  60445. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  60446. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  60447. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  60448. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  60449. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  60450. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  60451. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  60452. this._scene.shadowsEnabled = true;
  60453. this._scene.particlesEnabled = true;
  60454. this._scene.postProcessesEnabled = true;
  60455. this._scene.collisionsEnabled = true;
  60456. this._scene.lightsEnabled = true;
  60457. this._scene.texturesEnabled = true;
  60458. this._scene.lensFlaresEnabled = true;
  60459. this._scene.proceduralTexturesEnabled = true;
  60460. this._scene.renderTargetsEnabled = true;
  60461. this._scene.probesEnabled = true;
  60462. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  60463. this._clearSkeletonViewers();
  60464. };
  60465. DebugLayer.prototype._clearSkeletonViewers = function () {
  60466. for (var index = 0; index < this._skeletonViewers.length; index++) {
  60467. this._skeletonViewers[index].dispose();
  60468. }
  60469. this._skeletonViewers = [];
  60470. };
  60471. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  60472. if (showUI === void 0) { showUI = true; }
  60473. if (camera === void 0) { camera = null; }
  60474. if (rootElement === void 0) { rootElement = null; }
  60475. if (this._enabled) {
  60476. return;
  60477. }
  60478. this._enabled = true;
  60479. if (camera) {
  60480. this._camera = camera;
  60481. }
  60482. else {
  60483. this._camera = this._scene.activeCamera;
  60484. }
  60485. this._showUI = showUI;
  60486. var engine = this._scene.getEngine();
  60487. this._globalDiv = document.createElement("div");
  60488. this._rootElement = rootElement || document.body;
  60489. this._rootElement.appendChild(this._globalDiv);
  60490. this._generateDOMelements();
  60491. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  60492. this._syncPositions();
  60493. this._scene.registerBeforeRender(this._syncData);
  60494. this._scene.registerAfterRender(this._syncUI);
  60495. };
  60496. DebugLayer.prototype._clearLabels = function () {
  60497. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  60498. for (var index = 0; index < this._scene.meshes.length; index++) {
  60499. var mesh = this._scene.meshes[index];
  60500. mesh.renderOverlay = false;
  60501. }
  60502. };
  60503. DebugLayer.prototype._generateheader = function (root, text) {
  60504. var header = document.createElement("div");
  60505. header.innerHTML = text + "&nbsp;";
  60506. header.style.textAlign = "right";
  60507. header.style.width = "100%";
  60508. header.style.color = "white";
  60509. header.style.backgroundColor = "Black";
  60510. header.style.padding = "5px 5px 4px 0px";
  60511. header.style.marginLeft = "-5px";
  60512. header.style.fontWeight = "bold";
  60513. root.appendChild(header);
  60514. };
  60515. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  60516. var label = document.createElement("label");
  60517. label.style.display = "inline";
  60518. label.innerHTML = title;
  60519. label.style.color = color;
  60520. root.appendChild(label);
  60521. root.appendChild(document.createElement("br"));
  60522. };
  60523. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  60524. if (tag === void 0) { tag = null; }
  60525. var label = document.createElement("label");
  60526. label.style.display = "inline";
  60527. var boundingBoxesCheckbox = document.createElement("input");
  60528. boundingBoxesCheckbox.type = "checkbox";
  60529. boundingBoxesCheckbox.checked = initialState;
  60530. boundingBoxesCheckbox.style.display = "inline";
  60531. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  60532. boundingBoxesCheckbox.style.verticalAlign = "sub";
  60533. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  60534. task(evt.target, tag);
  60535. });
  60536. label.appendChild(boundingBoxesCheckbox);
  60537. var container = document.createElement("span");
  60538. var leftPart = document.createElement("span");
  60539. var rightPart = document.createElement("span");
  60540. rightPart.style.cssFloat = "right";
  60541. leftPart.innerHTML = leftTitle;
  60542. rightPart.innerHTML = rightTitle;
  60543. rightPart.style.fontSize = "12px";
  60544. rightPart.style.maxWidth = "200px";
  60545. container.appendChild(leftPart);
  60546. container.appendChild(rightPart);
  60547. label.appendChild(container);
  60548. root.appendChild(label);
  60549. root.appendChild(document.createElement("br"));
  60550. };
  60551. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  60552. if (tag === void 0) { tag = null; }
  60553. var label = document.createElement("label");
  60554. label.style.display = "inline";
  60555. var checkBox = document.createElement("input");
  60556. checkBox.type = "checkbox";
  60557. checkBox.checked = initialState;
  60558. checkBox.style.display = "inline";
  60559. checkBox.style.margin = "0px 5px 0px 0px";
  60560. checkBox.style.verticalAlign = "sub";
  60561. checkBox.addEventListener("change", function (evt) {
  60562. task(evt.target, tag);
  60563. });
  60564. label.appendChild(checkBox);
  60565. label.appendChild(document.createTextNode(title));
  60566. root.appendChild(label);
  60567. root.appendChild(document.createElement("br"));
  60568. };
  60569. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  60570. if (tag === void 0) { tag = null; }
  60571. var button = document.createElement("button");
  60572. button.innerHTML = title;
  60573. button.style.height = "24px";
  60574. button.style.width = "150px";
  60575. button.style.marginBottom = "5px";
  60576. button.style.color = "#444444";
  60577. button.style.border = "1px solid white";
  60578. button.className = "debugLayerButton";
  60579. button.addEventListener("click", function (evt) {
  60580. task(evt.target, tag);
  60581. });
  60582. root.appendChild(button);
  60583. root.appendChild(document.createElement("br"));
  60584. };
  60585. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  60586. if (tag === void 0) { tag = null; }
  60587. var label = document.createElement("label");
  60588. label.style.display = "inline";
  60589. var boundingBoxesRadio = document.createElement("input");
  60590. boundingBoxesRadio.type = "radio";
  60591. boundingBoxesRadio.name = name;
  60592. boundingBoxesRadio.checked = initialState;
  60593. boundingBoxesRadio.style.display = "inline";
  60594. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  60595. boundingBoxesRadio.style.verticalAlign = "sub";
  60596. boundingBoxesRadio.addEventListener("change", function (evt) {
  60597. task(evt.target, tag);
  60598. });
  60599. label.appendChild(boundingBoxesRadio);
  60600. label.appendChild(document.createTextNode(title));
  60601. root.appendChild(label);
  60602. root.appendChild(document.createElement("br"));
  60603. };
  60604. DebugLayer.prototype._generateDOMelements = function () {
  60605. var _this = this;
  60606. this._globalDiv.id = "DebugLayer";
  60607. this._globalDiv.style.position = "absolute";
  60608. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  60609. this._globalDiv.style.fontSize = "14px";
  60610. this._globalDiv.style.color = "white";
  60611. // Drawing canvas
  60612. this._drawingCanvas = document.createElement("canvas");
  60613. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  60614. this._drawingCanvas.style.position = "absolute";
  60615. this._drawingCanvas.style.pointerEvents = "none";
  60616. this._drawingCanvas.style.backgroundColor = "transparent";
  60617. this._drawingContext = this._drawingCanvas.getContext("2d");
  60618. this._globalDiv.appendChild(this._drawingCanvas);
  60619. if (this._showUI) {
  60620. var background = "rgba(128, 128, 128, 0.4)";
  60621. var border = "rgb(180, 180, 180) solid 1px";
  60622. // Stats
  60623. this._statsDiv = document.createElement("div");
  60624. this._statsDiv.id = "DebugLayerStats";
  60625. this._statsDiv.style.border = border;
  60626. this._statsDiv.style.position = "absolute";
  60627. this._statsDiv.style.background = background;
  60628. this._statsDiv.style.padding = "0px 0px 0px 5px";
  60629. this._generateheader(this._statsDiv, "STATISTICS");
  60630. this._statsSubsetDiv = document.createElement("div");
  60631. this._statsSubsetDiv.style.paddingTop = "5px";
  60632. this._statsSubsetDiv.style.paddingBottom = "5px";
  60633. this._statsSubsetDiv.style.overflowY = "auto";
  60634. this._statsDiv.appendChild(this._statsSubsetDiv);
  60635. // Tree
  60636. this._treeDiv = document.createElement("div");
  60637. this._treeDiv.id = "DebugLayerTree";
  60638. this._treeDiv.style.border = border;
  60639. this._treeDiv.style.position = "absolute";
  60640. this._treeDiv.style.background = background;
  60641. this._treeDiv.style.padding = "0px 0px 0px 5px";
  60642. this._treeDiv.style.display = "none";
  60643. this._generateheader(this._treeDiv, "MESHES TREE");
  60644. this._treeSubsetDiv = document.createElement("div");
  60645. this._treeSubsetDiv.style.paddingTop = "5px";
  60646. this._treeSubsetDiv.style.paddingRight = "5px";
  60647. this._treeSubsetDiv.style.overflowY = "auto";
  60648. this._treeSubsetDiv.style.maxHeight = "300px";
  60649. this._treeDiv.appendChild(this._treeSubsetDiv);
  60650. this._needToRefreshMeshesTree = true;
  60651. // Logs
  60652. this._logDiv = document.createElement("div");
  60653. this._logDiv.style.border = border;
  60654. this._logDiv.id = "DebugLayerLogs";
  60655. this._logDiv.style.position = "absolute";
  60656. this._logDiv.style.background = background;
  60657. this._logDiv.style.padding = "0px 0px 0px 5px";
  60658. this._logDiv.style.display = "none";
  60659. this._generateheader(this._logDiv, "LOGS");
  60660. this._logSubsetDiv = document.createElement("div");
  60661. this._logSubsetDiv.style.height = "127px";
  60662. this._logSubsetDiv.style.paddingTop = "5px";
  60663. this._logSubsetDiv.style.overflowY = "auto";
  60664. this._logSubsetDiv.style.fontSize = "12px";
  60665. this._logSubsetDiv.style.fontFamily = "consolas";
  60666. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  60667. this._logDiv.appendChild(this._logSubsetDiv);
  60668. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  60669. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  60670. };
  60671. // Options
  60672. this._optionsDiv = document.createElement("div");
  60673. this._optionsDiv.id = "DebugLayerOptions";
  60674. this._optionsDiv.style.border = border;
  60675. this._optionsDiv.style.position = "absolute";
  60676. this._optionsDiv.style.background = background;
  60677. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  60678. this._optionsDiv.style.overflowY = "auto";
  60679. this._generateheader(this._optionsDiv, "OPTIONS");
  60680. this._optionsSubsetDiv = document.createElement("div");
  60681. this._optionsSubsetDiv.style.paddingTop = "5px";
  60682. this._optionsSubsetDiv.style.paddingBottom = "5px";
  60683. this._optionsSubsetDiv.style.overflowY = "auto";
  60684. this._optionsSubsetDiv.style.maxHeight = "200px";
  60685. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  60686. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  60687. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  60688. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  60689. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  60690. _this._displayTree = element.checked;
  60691. _this._needToRefreshMeshesTree = true;
  60692. });
  60693. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60694. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  60695. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  60696. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  60697. _this._labelsEnabled = element.checked;
  60698. if (!_this._labelsEnabled) {
  60699. _this._clearLabels();
  60700. }
  60701. });
  60702. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  60703. if (element.checked) {
  60704. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  60705. }
  60706. else {
  60707. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  60708. }
  60709. });
  60710. ;
  60711. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60712. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  60713. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  60714. if (element.checked) {
  60715. _this._scene.forceWireframe = false;
  60716. _this._scene.forcePointsCloud = false;
  60717. }
  60718. });
  60719. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  60720. if (element.checked) {
  60721. _this._scene.forceWireframe = true;
  60722. _this._scene.forcePointsCloud = false;
  60723. }
  60724. });
  60725. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  60726. if (element.checked) {
  60727. _this._scene.forceWireframe = false;
  60728. _this._scene.forcePointsCloud = true;
  60729. }
  60730. });
  60731. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60732. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  60733. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  60734. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  60735. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  60736. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  60737. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  60738. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  60739. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  60740. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  60741. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  60742. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  60743. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  60744. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60745. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  60746. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  60747. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  60748. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  60749. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  60750. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  60751. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  60752. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  60753. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  60754. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  60755. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  60756. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  60757. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  60758. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  60759. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  60760. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  60761. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60762. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  60763. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  60764. if (element.checked) {
  60765. _this._scene.headphone = true;
  60766. }
  60767. });
  60768. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  60769. if (element.checked) {
  60770. _this._scene.headphone = false;
  60771. }
  60772. });
  60773. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  60774. _this._scene.audioEnabled = !element.checked;
  60775. });
  60776. }
  60777. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60778. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  60779. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  60780. if (!element.checked) {
  60781. _this._clearSkeletonViewers();
  60782. return;
  60783. }
  60784. for (var index = 0; index < _this._scene.meshes.length; index++) {
  60785. var mesh = _this._scene.meshes[index];
  60786. if (mesh.skeleton) {
  60787. var found = false;
  60788. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  60789. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  60790. found = true;
  60791. break;
  60792. }
  60793. }
  60794. if (found) {
  60795. continue;
  60796. }
  60797. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  60798. viewer.isEnabled = true;
  60799. _this._skeletonViewers.push(viewer);
  60800. }
  60801. }
  60802. });
  60803. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60804. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  60805. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  60806. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  60807. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  60808. if (_this._camera) {
  60809. console.log(_this._camera);
  60810. }
  60811. else {
  60812. console.warn("No camera defined, or debug layer created before camera creation!");
  60813. }
  60814. });
  60815. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  60816. this._globalDiv.appendChild(this._statsDiv);
  60817. this._globalDiv.appendChild(this._logDiv);
  60818. this._globalDiv.appendChild(this._optionsDiv);
  60819. this._globalDiv.appendChild(this._treeDiv);
  60820. }
  60821. };
  60822. DebugLayer.prototype._displayStats = function () {
  60823. var scene = this._scene;
  60824. var engine = scene.getEngine();
  60825. var glInfo = engine.getGlInfo();
  60826. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  60827. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60828. + "<b>Count</b><br>"
  60829. + "Total meshes: " + scene.meshes.length + "<br>"
  60830. + "Total lights: " + scene.lights.length + "<br>"
  60831. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  60832. + "Total materials: " + scene.materials.length + "<br>"
  60833. + "Total textures: " + scene.textures.length + "<br>"
  60834. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  60835. + "Active indices: " + scene.getActiveIndices() + "<br>"
  60836. + "Active bones: " + scene.getActiveBones() + "<br>"
  60837. + "Active particles: " + scene.getActiveParticles() + "<br>"
  60838. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  60839. + "<b>Duration</b><br>"
  60840. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  60841. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  60842. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  60843. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  60844. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  60845. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  60846. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  60847. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  60848. + "</div>"
  60849. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60850. + "<b>Extensions</b><br>"
  60851. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  60852. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  60853. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  60854. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  60855. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  60856. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  60857. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  60858. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  60859. + "</div><br>"
  60860. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  60861. + "<b>Caps.</b><br>"
  60862. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  60863. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  60864. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  60865. + "<b>Info</b><br>"
  60866. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  60867. + glInfo.version + "<br>"
  60868. + "</div><br>"
  60869. + glInfo.renderer + "<br>";
  60870. if (this.customStatsFunction) {
  60871. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  60872. }
  60873. };
  60874. return DebugLayer;
  60875. })();
  60876. BABYLON.DebugLayer = DebugLayer;
  60877. })(BABYLON || (BABYLON = {}));
  60878. 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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\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>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\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}","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}"};
  60879. 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"};
  60880. 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={}));";
  60881. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  60882. module.exports = BABYLON;
  60883. };