cannon-es.js 347 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107
  1. /**
  2. * Records what objects are colliding with each other
  3. */
  4. class ObjectCollisionMatrix {
  5. /**
  6. * The matrix storage.
  7. */
  8. /**
  9. * @todo Remove useless constructor
  10. */
  11. constructor() {
  12. this.matrix = void 0;
  13. this.matrix = {};
  14. }
  15. /**
  16. * get
  17. */
  18. get(bi, bj) {
  19. let {
  20. id: i
  21. } = bi;
  22. let {
  23. id: j
  24. } = bj;
  25. if (j > i) {
  26. const temp = j;
  27. j = i;
  28. i = temp;
  29. }
  30. return i + "-" + j in this.matrix;
  31. }
  32. /**
  33. * set
  34. */
  35. set(bi, bj, value) {
  36. let {
  37. id: i
  38. } = bi;
  39. let {
  40. id: j
  41. } = bj;
  42. if (j > i) {
  43. const temp = j;
  44. j = i;
  45. i = temp;
  46. }
  47. if (value) {
  48. this.matrix[i + "-" + j] = true;
  49. } else {
  50. delete this.matrix[i + "-" + j];
  51. }
  52. }
  53. /**
  54. * Empty the matrix
  55. */
  56. reset() {
  57. this.matrix = {};
  58. }
  59. /**
  60. * Set max number of objects
  61. */
  62. setNumObjects(n) {}
  63. }
  64. /**
  65. * A 3x3 matrix.
  66. * Authored by {@link http://github.com/schteppe/ schteppe}
  67. */
  68. class Mat3 {
  69. /**
  70. * A vector of length 9, containing all matrix elements.
  71. */
  72. /**
  73. * @param elements A vector of length 9, containing all matrix elements.
  74. */
  75. constructor(elements = [0, 0, 0, 0, 0, 0, 0, 0, 0]) {
  76. this.elements = void 0;
  77. this.elements = elements;
  78. }
  79. /**
  80. * Sets the matrix to identity
  81. * @todo Should perhaps be renamed to `setIdentity()` to be more clear.
  82. * @todo Create another function that immediately creates an identity matrix eg. `eye()`
  83. */
  84. identity() {
  85. const e = this.elements;
  86. e[0] = 1;
  87. e[1] = 0;
  88. e[2] = 0;
  89. e[3] = 0;
  90. e[4] = 1;
  91. e[5] = 0;
  92. e[6] = 0;
  93. e[7] = 0;
  94. e[8] = 1;
  95. }
  96. /**
  97. * Set all elements to zero
  98. */
  99. setZero() {
  100. const e = this.elements;
  101. e[0] = 0;
  102. e[1] = 0;
  103. e[2] = 0;
  104. e[3] = 0;
  105. e[4] = 0;
  106. e[5] = 0;
  107. e[6] = 0;
  108. e[7] = 0;
  109. e[8] = 0;
  110. }
  111. /**
  112. * Sets the matrix diagonal elements from a Vec3
  113. */
  114. setTrace(vector) {
  115. const e = this.elements;
  116. e[0] = vector.x;
  117. e[4] = vector.y;
  118. e[8] = vector.z;
  119. }
  120. /**
  121. * Gets the matrix diagonal elements
  122. */
  123. getTrace(target = new Vec3()) {
  124. const e = this.elements;
  125. target.x = e[0];
  126. target.y = e[4];
  127. target.z = e[8];
  128. return target;
  129. }
  130. /**
  131. * Matrix-Vector multiplication
  132. * @param v The vector to multiply with
  133. * @param target Optional, target to save the result in.
  134. */
  135. vmult(v, target = new Vec3()) {
  136. const e = this.elements;
  137. const x = v.x;
  138. const y = v.y;
  139. const z = v.z;
  140. target.x = e[0] * x + e[1] * y + e[2] * z;
  141. target.y = e[3] * x + e[4] * y + e[5] * z;
  142. target.z = e[6] * x + e[7] * y + e[8] * z;
  143. return target;
  144. }
  145. /**
  146. * Matrix-scalar multiplication
  147. */
  148. smult(s) {
  149. for (let i = 0; i < this.elements.length; i++) {
  150. this.elements[i] *= s;
  151. }
  152. }
  153. /**
  154. * Matrix multiplication
  155. * @param matrix Matrix to multiply with from left side.
  156. */
  157. mmult(matrix, target = new Mat3()) {
  158. const A = this.elements;
  159. const B = matrix.elements;
  160. const T = target.elements;
  161. const a11 = A[0],
  162. a12 = A[1],
  163. a13 = A[2],
  164. a21 = A[3],
  165. a22 = A[4],
  166. a23 = A[5],
  167. a31 = A[6],
  168. a32 = A[7],
  169. a33 = A[8];
  170. const b11 = B[0],
  171. b12 = B[1],
  172. b13 = B[2],
  173. b21 = B[3],
  174. b22 = B[4],
  175. b23 = B[5],
  176. b31 = B[6],
  177. b32 = B[7],
  178. b33 = B[8];
  179. T[0] = a11 * b11 + a12 * b21 + a13 * b31;
  180. T[1] = a11 * b12 + a12 * b22 + a13 * b32;
  181. T[2] = a11 * b13 + a12 * b23 + a13 * b33;
  182. T[3] = a21 * b11 + a22 * b21 + a23 * b31;
  183. T[4] = a21 * b12 + a22 * b22 + a23 * b32;
  184. T[5] = a21 * b13 + a22 * b23 + a23 * b33;
  185. T[6] = a31 * b11 + a32 * b21 + a33 * b31;
  186. T[7] = a31 * b12 + a32 * b22 + a33 * b32;
  187. T[8] = a31 * b13 + a32 * b23 + a33 * b33;
  188. return target;
  189. }
  190. /**
  191. * Scale each column of the matrix
  192. */
  193. scale(vector, target = new Mat3()) {
  194. const e = this.elements;
  195. const t = target.elements;
  196. for (let i = 0; i !== 3; i++) {
  197. t[3 * i + 0] = vector.x * e[3 * i + 0];
  198. t[3 * i + 1] = vector.y * e[3 * i + 1];
  199. t[3 * i + 2] = vector.z * e[3 * i + 2];
  200. }
  201. return target;
  202. }
  203. /**
  204. * Solve Ax=b
  205. * @param b The right hand side
  206. * @param target Optional. Target vector to save in.
  207. * @return The solution x
  208. * @todo should reuse arrays
  209. */
  210. solve(b, target = new Vec3()) {
  211. // Construct equations
  212. const nr = 3; // num rows
  213. const nc = 4; // num cols
  214. const eqns = [];
  215. let i;
  216. let j;
  217. for (i = 0; i < nr * nc; i++) {
  218. eqns.push(0);
  219. }
  220. for (i = 0; i < 3; i++) {
  221. for (j = 0; j < 3; j++) {
  222. eqns[i + nc * j] = this.elements[i + 3 * j];
  223. }
  224. }
  225. eqns[3 + 4 * 0] = b.x;
  226. eqns[3 + 4 * 1] = b.y;
  227. eqns[3 + 4 * 2] = b.z; // Compute right upper triangular version of the matrix - Gauss elimination
  228. let n = 3;
  229. const k = n;
  230. let np;
  231. const kp = 4; // num rows
  232. let p;
  233. do {
  234. i = k - n;
  235. if (eqns[i + nc * i] === 0) {
  236. // the pivot is null, swap lines
  237. for (j = i + 1; j < k; j++) {
  238. if (eqns[i + nc * j] !== 0) {
  239. np = kp;
  240. do {
  241. // do ligne( i ) = ligne( i ) + ligne( k )
  242. p = kp - np;
  243. eqns[p + nc * i] += eqns[p + nc * j];
  244. } while (--np);
  245. break;
  246. }
  247. }
  248. }
  249. if (eqns[i + nc * i] !== 0) {
  250. for (j = i + 1; j < k; j++) {
  251. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  252. np = kp;
  253. do {
  254. // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  255. p = kp - np;
  256. eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  257. } while (--np);
  258. }
  259. }
  260. } while (--n); // Get the solution
  261. target.z = eqns[2 * nc + 3] / eqns[2 * nc + 2];
  262. target.y = (eqns[1 * nc + 3] - eqns[1 * nc + 2] * target.z) / eqns[1 * nc + 1];
  263. target.x = (eqns[0 * nc + 3] - eqns[0 * nc + 2] * target.z - eqns[0 * nc + 1] * target.y) / eqns[0 * nc + 0];
  264. if (isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x === Infinity || target.y === Infinity || target.z === Infinity) {
  265. throw "Could not solve equation! Got x=[" + target.toString() + "], b=[" + b.toString() + "], A=[" + this.toString() + "]";
  266. }
  267. return target;
  268. }
  269. /**
  270. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  271. * @param value If provided, the matrix element will be set to this value.
  272. */
  273. e(row, column, value) {
  274. if (value === undefined) {
  275. return this.elements[column + 3 * row];
  276. } else {
  277. // Set value
  278. this.elements[column + 3 * row] = value;
  279. }
  280. }
  281. /**
  282. * Copy another matrix into this matrix object.
  283. */
  284. copy(matrix) {
  285. for (let i = 0; i < matrix.elements.length; i++) {
  286. this.elements[i] = matrix.elements[i];
  287. }
  288. return this;
  289. }
  290. /**
  291. * Returns a string representation of the matrix.
  292. */
  293. toString() {
  294. let r = '';
  295. const sep = ',';
  296. for (let i = 0; i < 9; i++) {
  297. r += this.elements[i] + sep;
  298. }
  299. return r;
  300. }
  301. /**
  302. * reverse the matrix
  303. * @param target Target matrix to save in.
  304. * @return The solution x
  305. */
  306. reverse(target = new Mat3()) {
  307. // Construct equations
  308. const nr = 3; // num rows
  309. const nc = 6; // num cols
  310. const eqns = reverse_eqns;
  311. let i;
  312. let j;
  313. for (i = 0; i < 3; i++) {
  314. for (j = 0; j < 3; j++) {
  315. eqns[i + nc * j] = this.elements[i + 3 * j];
  316. }
  317. }
  318. eqns[3 + 6 * 0] = 1;
  319. eqns[3 + 6 * 1] = 0;
  320. eqns[3 + 6 * 2] = 0;
  321. eqns[4 + 6 * 0] = 0;
  322. eqns[4 + 6 * 1] = 1;
  323. eqns[4 + 6 * 2] = 0;
  324. eqns[5 + 6 * 0] = 0;
  325. eqns[5 + 6 * 1] = 0;
  326. eqns[5 + 6 * 2] = 1; // Compute right upper triangular version of the matrix - Gauss elimination
  327. let n = 3;
  328. const k = n;
  329. let np;
  330. const kp = nc; // num rows
  331. let p;
  332. do {
  333. i = k - n;
  334. if (eqns[i + nc * i] === 0) {
  335. // the pivot is null, swap lines
  336. for (j = i + 1; j < k; j++) {
  337. if (eqns[i + nc * j] !== 0) {
  338. np = kp;
  339. do {
  340. // do line( i ) = line( i ) + line( k )
  341. p = kp - np;
  342. eqns[p + nc * i] += eqns[p + nc * j];
  343. } while (--np);
  344. break;
  345. }
  346. }
  347. }
  348. if (eqns[i + nc * i] !== 0) {
  349. for (j = i + 1; j < k; j++) {
  350. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  351. np = kp;
  352. do {
  353. // do line( k ) = line( k ) - multiplier * line( i )
  354. p = kp - np;
  355. eqns[p + nc * j] = p <= i ? 0 : eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  356. } while (--np);
  357. }
  358. }
  359. } while (--n); // eliminate the upper left triangle of the matrix
  360. i = 2;
  361. do {
  362. j = i - 1;
  363. do {
  364. const multiplier = eqns[i + nc * j] / eqns[i + nc * i];
  365. np = nc;
  366. do {
  367. p = nc - np;
  368. eqns[p + nc * j] = eqns[p + nc * j] - eqns[p + nc * i] * multiplier;
  369. } while (--np);
  370. } while (j--);
  371. } while (--i); // operations on the diagonal
  372. i = 2;
  373. do {
  374. const multiplier = 1 / eqns[i + nc * i];
  375. np = nc;
  376. do {
  377. p = nc - np;
  378. eqns[p + nc * i] = eqns[p + nc * i] * multiplier;
  379. } while (--np);
  380. } while (i--);
  381. i = 2;
  382. do {
  383. j = 2;
  384. do {
  385. p = eqns[nr + j + nc * i];
  386. if (isNaN(p) || p === Infinity) {
  387. throw "Could not reverse! A=[" + this.toString() + "]";
  388. }
  389. target.e(i, j, p);
  390. } while (j--);
  391. } while (i--);
  392. return target;
  393. }
  394. /**
  395. * Set the matrix from a quaterion
  396. */
  397. setRotationFromQuaternion(q) {
  398. const x = q.x;
  399. const y = q.y;
  400. const z = q.z;
  401. const w = q.w;
  402. const x2 = x + x;
  403. const y2 = y + y;
  404. const z2 = z + z;
  405. const xx = x * x2;
  406. const xy = x * y2;
  407. const xz = x * z2;
  408. const yy = y * y2;
  409. const yz = y * z2;
  410. const zz = z * z2;
  411. const wx = w * x2;
  412. const wy = w * y2;
  413. const wz = w * z2;
  414. const e = this.elements;
  415. e[3 * 0 + 0] = 1 - (yy + zz);
  416. e[3 * 0 + 1] = xy - wz;
  417. e[3 * 0 + 2] = xz + wy;
  418. e[3 * 1 + 0] = xy + wz;
  419. e[3 * 1 + 1] = 1 - (xx + zz);
  420. e[3 * 1 + 2] = yz - wx;
  421. e[3 * 2 + 0] = xz - wy;
  422. e[3 * 2 + 1] = yz + wx;
  423. e[3 * 2 + 2] = 1 - (xx + yy);
  424. return this;
  425. }
  426. /**
  427. * Transpose the matrix
  428. * @param target Optional. Where to store the result.
  429. * @return The target Mat3, or a new Mat3 if target was omitted.
  430. */
  431. transpose(target = new Mat3()) {
  432. const M = this.elements;
  433. const T = target.elements;
  434. let tmp; //Set diagonals
  435. T[0] = M[0];
  436. T[4] = M[4];
  437. T[8] = M[8];
  438. tmp = M[1];
  439. T[1] = M[3];
  440. T[3] = tmp;
  441. tmp = M[2];
  442. T[2] = M[6];
  443. T[6] = tmp;
  444. tmp = M[5];
  445. T[5] = M[7];
  446. T[7] = tmp;
  447. return target;
  448. }
  449. }
  450. const reverse_eqns = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  451. /**
  452. * 3-dimensional vector
  453. * @example
  454. * const v = new Vec3(1, 2, 3)
  455. * console.log('x=' + v.x) // x=1
  456. */
  457. class Vec3 {
  458. constructor(x = 0.0, y = 0.0, z = 0.0) {
  459. this.x = void 0;
  460. this.y = void 0;
  461. this.z = void 0;
  462. this.x = x;
  463. this.y = y;
  464. this.z = z;
  465. }
  466. /**
  467. * Vector cross product
  468. * @param target Optional target to save in.
  469. */
  470. cross(vector, target = new Vec3()) {
  471. const vx = vector.x;
  472. const vy = vector.y;
  473. const vz = vector.z;
  474. const x = this.x;
  475. const y = this.y;
  476. const z = this.z;
  477. target.x = y * vz - z * vy;
  478. target.y = z * vx - x * vz;
  479. target.z = x * vy - y * vx;
  480. return target;
  481. }
  482. /**
  483. * Set the vectors' 3 elements
  484. */
  485. set(x, y, z) {
  486. this.x = x;
  487. this.y = y;
  488. this.z = z;
  489. return this;
  490. }
  491. /**
  492. * Set all components of the vector to zero.
  493. */
  494. setZero() {
  495. this.x = this.y = this.z = 0;
  496. }
  497. /**
  498. * Vector addition
  499. */
  500. vadd(vector, target) {
  501. if (target) {
  502. target.x = vector.x + this.x;
  503. target.y = vector.y + this.y;
  504. target.z = vector.z + this.z;
  505. } else {
  506. return new Vec3(this.x + vector.x, this.y + vector.y, this.z + vector.z);
  507. }
  508. }
  509. /**
  510. * Vector subtraction
  511. * @param target Optional target to save in.
  512. */
  513. vsub(vector, target) {
  514. if (target) {
  515. target.x = this.x - vector.x;
  516. target.y = this.y - vector.y;
  517. target.z = this.z - vector.z;
  518. } else {
  519. return new Vec3(this.x - vector.x, this.y - vector.y, this.z - vector.z);
  520. }
  521. }
  522. /**
  523. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  524. *
  525. * See {@link https://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf Umeå University Lecture}
  526. */
  527. crossmat() {
  528. return new Mat3([0, -this.z, this.y, this.z, 0, -this.x, -this.y, this.x, 0]);
  529. }
  530. /**
  531. * Normalize the vector. Note that this changes the values in the vector.
  532. * @return Returns the norm of the vector
  533. */
  534. normalize() {
  535. const x = this.x;
  536. const y = this.y;
  537. const z = this.z;
  538. const n = Math.sqrt(x * x + y * y + z * z);
  539. if (n > 0.0) {
  540. const invN = 1 / n;
  541. this.x *= invN;
  542. this.y *= invN;
  543. this.z *= invN;
  544. } else {
  545. // Make something up
  546. this.x = 0;
  547. this.y = 0;
  548. this.z = 0;
  549. }
  550. return n;
  551. }
  552. /**
  553. * Get the version of this vector that is of length 1.
  554. * @param target Optional target to save in
  555. * @return Returns the unit vector
  556. */
  557. unit(target = new Vec3()) {
  558. const x = this.x;
  559. const y = this.y;
  560. const z = this.z;
  561. let ninv = Math.sqrt(x * x + y * y + z * z);
  562. if (ninv > 0.0) {
  563. ninv = 1.0 / ninv;
  564. target.x = x * ninv;
  565. target.y = y * ninv;
  566. target.z = z * ninv;
  567. } else {
  568. target.x = 1;
  569. target.y = 0;
  570. target.z = 0;
  571. }
  572. return target;
  573. }
  574. /**
  575. * Get the length of the vector
  576. */
  577. length() {
  578. const x = this.x;
  579. const y = this.y;
  580. const z = this.z;
  581. return Math.sqrt(x * x + y * y + z * z);
  582. }
  583. /**
  584. * Get the squared length of the vector.
  585. */
  586. lengthSquared() {
  587. return this.dot(this);
  588. }
  589. /**
  590. * Get distance from this point to another point
  591. */
  592. distanceTo(p) {
  593. const x = this.x;
  594. const y = this.y;
  595. const z = this.z;
  596. const px = p.x;
  597. const py = p.y;
  598. const pz = p.z;
  599. return Math.sqrt((px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z));
  600. }
  601. /**
  602. * Get squared distance from this point to another point
  603. */
  604. distanceSquared(p) {
  605. const x = this.x;
  606. const y = this.y;
  607. const z = this.z;
  608. const px = p.x;
  609. const py = p.y;
  610. const pz = p.z;
  611. return (px - x) * (px - x) + (py - y) * (py - y) + (pz - z) * (pz - z);
  612. }
  613. /**
  614. * Multiply all the components of the vector with a scalar.
  615. * @param target The vector to save the result in.
  616. */
  617. scale(scalar, target = new Vec3()) {
  618. const x = this.x;
  619. const y = this.y;
  620. const z = this.z;
  621. target.x = scalar * x;
  622. target.y = scalar * y;
  623. target.z = scalar * z;
  624. return target;
  625. }
  626. /**
  627. * Multiply the vector with an other vector, component-wise.
  628. * @param target The vector to save the result in.
  629. */
  630. vmul(vector, target = new Vec3()) {
  631. target.x = vector.x * this.x;
  632. target.y = vector.y * this.y;
  633. target.z = vector.z * this.z;
  634. return target;
  635. }
  636. /**
  637. * Scale a vector and add it to this vector. Save the result in "target". (target = this + vector * scalar)
  638. * @param target The vector to save the result in.
  639. */
  640. addScaledVector(scalar, vector, target = new Vec3()) {
  641. target.x = this.x + scalar * vector.x;
  642. target.y = this.y + scalar * vector.y;
  643. target.z = this.z + scalar * vector.z;
  644. return target;
  645. }
  646. /**
  647. * Calculate dot product
  648. * @param vector
  649. */
  650. dot(vector) {
  651. return this.x * vector.x + this.y * vector.y + this.z * vector.z;
  652. }
  653. isZero() {
  654. return this.x === 0 && this.y === 0 && this.z === 0;
  655. }
  656. /**
  657. * Make the vector point in the opposite direction.
  658. * @param target Optional target to save in
  659. */
  660. negate(target = new Vec3()) {
  661. target.x = -this.x;
  662. target.y = -this.y;
  663. target.z = -this.z;
  664. return target;
  665. }
  666. /**
  667. * Compute two artificial tangents to the vector
  668. * @param t1 Vector object to save the first tangent in
  669. * @param t2 Vector object to save the second tangent in
  670. */
  671. tangents(t1, t2) {
  672. const norm = this.length();
  673. if (norm > 0.0) {
  674. const n = Vec3_tangents_n;
  675. const inorm = 1 / norm;
  676. n.set(this.x * inorm, this.y * inorm, this.z * inorm);
  677. const randVec = Vec3_tangents_randVec;
  678. if (Math.abs(n.x) < 0.9) {
  679. randVec.set(1, 0, 0);
  680. n.cross(randVec, t1);
  681. } else {
  682. randVec.set(0, 1, 0);
  683. n.cross(randVec, t1);
  684. }
  685. n.cross(t1, t2);
  686. } else {
  687. // The normal length is zero, make something up
  688. t1.set(1, 0, 0);
  689. t2.set(0, 1, 0);
  690. }
  691. }
  692. /**
  693. * Converts to a more readable format
  694. */
  695. toString() {
  696. return this.x + "," + this.y + "," + this.z;
  697. }
  698. /**
  699. * Converts to an array
  700. */
  701. toArray() {
  702. return [this.x, this.y, this.z];
  703. }
  704. /**
  705. * Copies value of source to this vector.
  706. */
  707. copy(vector) {
  708. this.x = vector.x;
  709. this.y = vector.y;
  710. this.z = vector.z;
  711. return this;
  712. }
  713. /**
  714. * Do a linear interpolation between two vectors
  715. * @param t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.
  716. */
  717. lerp(vector, t, target) {
  718. const x = this.x;
  719. const y = this.y;
  720. const z = this.z;
  721. target.x = x + (vector.x - x) * t;
  722. target.y = y + (vector.y - y) * t;
  723. target.z = z + (vector.z - z) * t;
  724. }
  725. /**
  726. * Check if a vector equals is almost equal to another one.
  727. */
  728. almostEquals(vector, precision = 1e-6) {
  729. if (Math.abs(this.x - vector.x) > precision || Math.abs(this.y - vector.y) > precision || Math.abs(this.z - vector.z) > precision) {
  730. return false;
  731. }
  732. return true;
  733. }
  734. /**
  735. * Check if a vector is almost zero
  736. */
  737. almostZero(precision = 1e-6) {
  738. if (Math.abs(this.x) > precision || Math.abs(this.y) > precision || Math.abs(this.z) > precision) {
  739. return false;
  740. }
  741. return true;
  742. }
  743. /**
  744. * Check if the vector is anti-parallel to another vector.
  745. * @param precision Set to zero for exact comparisons
  746. */
  747. isAntiparallelTo(vector, precision) {
  748. this.negate(antip_neg);
  749. return antip_neg.almostEquals(vector, precision);
  750. }
  751. /**
  752. * Clone the vector
  753. */
  754. clone() {
  755. return new Vec3(this.x, this.y, this.z);
  756. }
  757. }
  758. Vec3.ZERO = void 0;
  759. Vec3.UNIT_X = void 0;
  760. Vec3.UNIT_Y = void 0;
  761. Vec3.UNIT_Z = void 0;
  762. Vec3.ZERO = new Vec3(0, 0, 0);
  763. Vec3.UNIT_X = new Vec3(1, 0, 0);
  764. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  765. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  766. const Vec3_tangents_n = new Vec3();
  767. const Vec3_tangents_randVec = new Vec3();
  768. const antip_neg = new Vec3();
  769. /**
  770. * Axis aligned bounding box class.
  771. */
  772. class AABB {
  773. /**
  774. * The lower bound of the bounding box
  775. */
  776. /**
  777. * The upper bound of the bounding box
  778. */
  779. constructor(options = {}) {
  780. this.lowerBound = void 0;
  781. this.upperBound = void 0;
  782. this.lowerBound = new Vec3();
  783. this.upperBound = new Vec3();
  784. if (options.lowerBound) {
  785. this.lowerBound.copy(options.lowerBound);
  786. }
  787. if (options.upperBound) {
  788. this.upperBound.copy(options.upperBound);
  789. }
  790. }
  791. /**
  792. * Set the AABB bounds from a set of points.
  793. * @param points An array of Vec3's.
  794. * @return The self object
  795. */
  796. setFromPoints(points, position, quaternion, skinSize) {
  797. const l = this.lowerBound;
  798. const u = this.upperBound;
  799. const q = quaternion; // Set to the first point
  800. l.copy(points[0]);
  801. if (q) {
  802. q.vmult(l, l);
  803. }
  804. u.copy(l);
  805. for (let i = 1; i < points.length; i++) {
  806. let p = points[i];
  807. if (q) {
  808. q.vmult(p, tmp$1);
  809. p = tmp$1;
  810. }
  811. if (p.x > u.x) {
  812. u.x = p.x;
  813. }
  814. if (p.x < l.x) {
  815. l.x = p.x;
  816. }
  817. if (p.y > u.y) {
  818. u.y = p.y;
  819. }
  820. if (p.y < l.y) {
  821. l.y = p.y;
  822. }
  823. if (p.z > u.z) {
  824. u.z = p.z;
  825. }
  826. if (p.z < l.z) {
  827. l.z = p.z;
  828. }
  829. } // Add offset
  830. if (position) {
  831. position.vadd(l, l);
  832. position.vadd(u, u);
  833. }
  834. if (skinSize) {
  835. l.x -= skinSize;
  836. l.y -= skinSize;
  837. l.z -= skinSize;
  838. u.x += skinSize;
  839. u.y += skinSize;
  840. u.z += skinSize;
  841. }
  842. return this;
  843. }
  844. /**
  845. * Copy bounds from an AABB to this AABB
  846. * @param aabb Source to copy from
  847. * @return The this object, for chainability
  848. */
  849. copy(aabb) {
  850. this.lowerBound.copy(aabb.lowerBound);
  851. this.upperBound.copy(aabb.upperBound);
  852. return this;
  853. }
  854. /**
  855. * Clone an AABB
  856. */
  857. clone() {
  858. return new AABB().copy(this);
  859. }
  860. /**
  861. * Extend this AABB so that it covers the given AABB too.
  862. */
  863. extend(aabb) {
  864. this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);
  865. this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);
  866. this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);
  867. this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);
  868. this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);
  869. this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);
  870. }
  871. /**
  872. * Returns true if the given AABB overlaps this AABB.
  873. */
  874. overlaps(aabb) {
  875. const l1 = this.lowerBound;
  876. const u1 = this.upperBound;
  877. const l2 = aabb.lowerBound;
  878. const u2 = aabb.upperBound; // l2 u2
  879. // |---------|
  880. // |--------|
  881. // l1 u1
  882. const overlapsX = l2.x <= u1.x && u1.x <= u2.x || l1.x <= u2.x && u2.x <= u1.x;
  883. const overlapsY = l2.y <= u1.y && u1.y <= u2.y || l1.y <= u2.y && u2.y <= u1.y;
  884. const overlapsZ = l2.z <= u1.z && u1.z <= u2.z || l1.z <= u2.z && u2.z <= u1.z;
  885. return overlapsX && overlapsY && overlapsZ;
  886. } // Mostly for debugging
  887. volume() {
  888. const l = this.lowerBound;
  889. const u = this.upperBound;
  890. return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);
  891. }
  892. /**
  893. * Returns true if the given AABB is fully contained in this AABB.
  894. */
  895. contains(aabb) {
  896. const l1 = this.lowerBound;
  897. const u1 = this.upperBound;
  898. const l2 = aabb.lowerBound;
  899. const u2 = aabb.upperBound; // l2 u2
  900. // |---------|
  901. // |---------------|
  902. // l1 u1
  903. return l1.x <= l2.x && u1.x >= u2.x && l1.y <= l2.y && u1.y >= u2.y && l1.z <= l2.z && u1.z >= u2.z;
  904. }
  905. getCorners(a, b, c, d, e, f, g, h) {
  906. const l = this.lowerBound;
  907. const u = this.upperBound;
  908. a.copy(l);
  909. b.set(u.x, l.y, l.z);
  910. c.set(u.x, u.y, l.z);
  911. d.set(l.x, u.y, u.z);
  912. e.set(u.x, l.y, u.z);
  913. f.set(l.x, u.y, l.z);
  914. g.set(l.x, l.y, u.z);
  915. h.copy(u);
  916. }
  917. /**
  918. * Get the representation of an AABB in another frame.
  919. * @return The "target" AABB object.
  920. */
  921. toLocalFrame(frame, target) {
  922. const corners = transformIntoFrame_corners;
  923. const a = corners[0];
  924. const b = corners[1];
  925. const c = corners[2];
  926. const d = corners[3];
  927. const e = corners[4];
  928. const f = corners[5];
  929. const g = corners[6];
  930. const h = corners[7]; // Get corners in current frame
  931. this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame
  932. for (let i = 0; i !== 8; i++) {
  933. const corner = corners[i];
  934. frame.pointToLocal(corner, corner);
  935. }
  936. return target.setFromPoints(corners);
  937. }
  938. /**
  939. * Get the representation of an AABB in the global frame.
  940. * @return The "target" AABB object.
  941. */
  942. toWorldFrame(frame, target) {
  943. const corners = transformIntoFrame_corners;
  944. const a = corners[0];
  945. const b = corners[1];
  946. const c = corners[2];
  947. const d = corners[3];
  948. const e = corners[4];
  949. const f = corners[5];
  950. const g = corners[6];
  951. const h = corners[7]; // Get corners in current frame
  952. this.getCorners(a, b, c, d, e, f, g, h); // Transform them to new local frame
  953. for (let i = 0; i !== 8; i++) {
  954. const corner = corners[i];
  955. frame.pointToWorld(corner, corner);
  956. }
  957. return target.setFromPoints(corners);
  958. }
  959. /**
  960. * Check if the AABB is hit by a ray.
  961. */
  962. overlapsRay(ray) {
  963. const {
  964. direction,
  965. from
  966. } = ray; // const t = 0
  967. // ray.direction is unit direction vector of ray
  968. const dirFracX = 1 / direction.x;
  969. const dirFracY = 1 / direction.y;
  970. const dirFracZ = 1 / direction.z; // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
  971. const t1 = (this.lowerBound.x - from.x) * dirFracX;
  972. const t2 = (this.upperBound.x - from.x) * dirFracX;
  973. const t3 = (this.lowerBound.y - from.y) * dirFracY;
  974. const t4 = (this.upperBound.y - from.y) * dirFracY;
  975. const t5 = (this.lowerBound.z - from.z) * dirFracZ;
  976. const t6 = (this.upperBound.z - from.z) * dirFracZ; // const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
  977. // const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
  978. const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
  979. const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
  980. if (tmax < 0) {
  981. //t = tmax;
  982. return false;
  983. } // if tmin > tmax, ray doesn't intersect AABB
  984. if (tmin > tmax) {
  985. //t = tmax;
  986. return false;
  987. }
  988. return true;
  989. }
  990. }
  991. const tmp$1 = new Vec3();
  992. const transformIntoFrame_corners = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  993. /**
  994. * Collision "matrix".
  995. * It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  996. */
  997. class ArrayCollisionMatrix {
  998. /**
  999. * The matrix storage.
  1000. */
  1001. constructor() {
  1002. this.matrix = void 0;
  1003. this.matrix = [];
  1004. }
  1005. /**
  1006. * Get an element
  1007. */
  1008. get(bi, bj) {
  1009. let {
  1010. index: i
  1011. } = bi;
  1012. let {
  1013. index: j
  1014. } = bj;
  1015. if (j > i) {
  1016. const temp = j;
  1017. j = i;
  1018. i = temp;
  1019. }
  1020. return this.matrix[(i * (i + 1) >> 1) + j - 1];
  1021. }
  1022. /**
  1023. * Set an element
  1024. */
  1025. set(bi, bj, value) {
  1026. let {
  1027. index: i
  1028. } = bi;
  1029. let {
  1030. index: j
  1031. } = bj;
  1032. if (j > i) {
  1033. const temp = j;
  1034. j = i;
  1035. i = temp;
  1036. }
  1037. this.matrix[(i * (i + 1) >> 1) + j - 1] = value ? 1 : 0;
  1038. }
  1039. /**
  1040. * Sets all elements to zero
  1041. */
  1042. reset() {
  1043. for (let i = 0, l = this.matrix.length; i !== l; i++) {
  1044. this.matrix[i] = 0;
  1045. }
  1046. }
  1047. /**
  1048. * Sets the max number of objects
  1049. */
  1050. setNumObjects(n) {
  1051. this.matrix.length = n * (n - 1) >> 1;
  1052. }
  1053. }
  1054. /**
  1055. * Base class for objects that dispatches events.
  1056. */
  1057. class EventTarget {
  1058. constructor() {
  1059. this._listeners = void 0;
  1060. }
  1061. /**
  1062. * Add an event listener
  1063. * @return The self object, for chainability.
  1064. */
  1065. addEventListener(type, listener) {
  1066. if (this._listeners === undefined) {
  1067. this._listeners = {};
  1068. }
  1069. const listeners = this._listeners;
  1070. if (listeners[type] === undefined) {
  1071. listeners[type] = [];
  1072. }
  1073. if (!listeners[type].includes(listener)) {
  1074. listeners[type].push(listener);
  1075. }
  1076. return this;
  1077. }
  1078. /**
  1079. * Check if an event listener is added
  1080. */
  1081. hasEventListener(type, listener) {
  1082. if (this._listeners === undefined) {
  1083. return false;
  1084. }
  1085. const listeners = this._listeners;
  1086. if (listeners[type] !== undefined && listeners[type].includes(listener)) {
  1087. return true;
  1088. }
  1089. return false;
  1090. }
  1091. /**
  1092. * Check if any event listener of the given type is added
  1093. */
  1094. hasAnyEventListener(type) {
  1095. if (this._listeners === undefined) {
  1096. return false;
  1097. }
  1098. const listeners = this._listeners;
  1099. return listeners[type] !== undefined;
  1100. }
  1101. /**
  1102. * Remove an event listener
  1103. * @return The self object, for chainability.
  1104. */
  1105. removeEventListener(type, listener) {
  1106. if (this._listeners === undefined) {
  1107. return this;
  1108. }
  1109. const listeners = this._listeners;
  1110. if (listeners[type] === undefined) {
  1111. return this;
  1112. }
  1113. const index = listeners[type].indexOf(listener);
  1114. if (index !== -1) {
  1115. listeners[type].splice(index, 1);
  1116. }
  1117. return this;
  1118. }
  1119. /**
  1120. * Emit an event.
  1121. * @return The self object, for chainability.
  1122. */
  1123. dispatchEvent(event) {
  1124. if (this._listeners === undefined) {
  1125. return this;
  1126. }
  1127. const listeners = this._listeners;
  1128. const listenerArray = listeners[event.type];
  1129. if (listenerArray !== undefined) {
  1130. event.target = this;
  1131. for (let i = 0, l = listenerArray.length; i < l; i++) {
  1132. listenerArray[i].call(this, event);
  1133. }
  1134. }
  1135. return this;
  1136. }
  1137. }
  1138. /**
  1139. * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.
  1140. * @param x Multiplier of the imaginary basis vector i.
  1141. * @param y Multiplier of the imaginary basis vector j.
  1142. * @param z Multiplier of the imaginary basis vector k.
  1143. * @param w Multiplier of the real part.
  1144. * @see http://en.wikipedia.org/wiki/Quaternion
  1145. */
  1146. class Quaternion {
  1147. constructor(x = 0, y = 0, z = 0, w = 1) {
  1148. this.x = void 0;
  1149. this.y = void 0;
  1150. this.z = void 0;
  1151. this.w = void 0;
  1152. this.x = x;
  1153. this.y = y;
  1154. this.z = z;
  1155. this.w = w;
  1156. }
  1157. /**
  1158. * Set the value of the quaternion.
  1159. */
  1160. set(x, y, z, w) {
  1161. this.x = x;
  1162. this.y = y;
  1163. this.z = z;
  1164. this.w = w;
  1165. return this;
  1166. }
  1167. /**
  1168. * Convert to a readable format
  1169. * @return "x,y,z,w"
  1170. */
  1171. toString() {
  1172. return this.x + "," + this.y + "," + this.z + "," + this.w;
  1173. }
  1174. /**
  1175. * Convert to an Array
  1176. * @return [x, y, z, w]
  1177. */
  1178. toArray() {
  1179. return [this.x, this.y, this.z, this.w];
  1180. }
  1181. /**
  1182. * Set the quaternion components given an axis and an angle in radians.
  1183. */
  1184. setFromAxisAngle(vector, angle) {
  1185. const s = Math.sin(angle * 0.5);
  1186. this.x = vector.x * s;
  1187. this.y = vector.y * s;
  1188. this.z = vector.z * s;
  1189. this.w = Math.cos(angle * 0.5);
  1190. return this;
  1191. }
  1192. /**
  1193. * Converts the quaternion to [ axis, angle ] representation.
  1194. * @param targetAxis A vector object to reuse for storing the axis.
  1195. * @return An array, first element is the axis and the second is the angle in radians.
  1196. */
  1197. toAxisAngle(targetAxis = new Vec3()) {
  1198. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  1199. const angle = 2 * Math.acos(this.w);
  1200. const s = Math.sqrt(1 - this.w * this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  1201. if (s < 0.001) {
  1202. // test to avoid divide by zero, s is always positive due to sqrt
  1203. // if s close to zero then direction of axis not important
  1204. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  1205. targetAxis.y = this.y;
  1206. targetAxis.z = this.z;
  1207. } else {
  1208. targetAxis.x = this.x / s; // normalise axis
  1209. targetAxis.y = this.y / s;
  1210. targetAxis.z = this.z / s;
  1211. }
  1212. return [targetAxis, angle];
  1213. }
  1214. /**
  1215. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  1216. */
  1217. setFromVectors(u, v) {
  1218. if (u.isAntiparallelTo(v)) {
  1219. const t1 = sfv_t1;
  1220. const t2 = sfv_t2;
  1221. u.tangents(t1, t2);
  1222. this.setFromAxisAngle(t1, Math.PI);
  1223. } else {
  1224. const a = u.cross(v);
  1225. this.x = a.x;
  1226. this.y = a.y;
  1227. this.z = a.z;
  1228. this.w = Math.sqrt(u.length() ** 2 * v.length() ** 2) + u.dot(v);
  1229. this.normalize();
  1230. }
  1231. return this;
  1232. }
  1233. /**
  1234. * Multiply the quaternion with an other quaternion.
  1235. */
  1236. mult(quat, target = new Quaternion()) {
  1237. const ax = this.x;
  1238. const ay = this.y;
  1239. const az = this.z;
  1240. const aw = this.w;
  1241. const bx = quat.x;
  1242. const by = quat.y;
  1243. const bz = quat.z;
  1244. const bw = quat.w;
  1245. target.x = ax * bw + aw * bx + ay * bz - az * by;
  1246. target.y = ay * bw + aw * by + az * bx - ax * bz;
  1247. target.z = az * bw + aw * bz + ax * by - ay * bx;
  1248. target.w = aw * bw - ax * bx - ay * by - az * bz;
  1249. return target;
  1250. }
  1251. /**
  1252. * Get the inverse quaternion rotation.
  1253. */
  1254. inverse(target = new Quaternion()) {
  1255. const x = this.x;
  1256. const y = this.y;
  1257. const z = this.z;
  1258. const w = this.w;
  1259. this.conjugate(target);
  1260. const inorm2 = 1 / (x * x + y * y + z * z + w * w);
  1261. target.x *= inorm2;
  1262. target.y *= inorm2;
  1263. target.z *= inorm2;
  1264. target.w *= inorm2;
  1265. return target;
  1266. }
  1267. /**
  1268. * Get the quaternion conjugate
  1269. */
  1270. conjugate(target = new Quaternion()) {
  1271. target.x = -this.x;
  1272. target.y = -this.y;
  1273. target.z = -this.z;
  1274. target.w = this.w;
  1275. return target;
  1276. }
  1277. /**
  1278. * Normalize the quaternion. Note that this changes the values of the quaternion.
  1279. */
  1280. normalize() {
  1281. let l = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1282. if (l === 0) {
  1283. this.x = 0;
  1284. this.y = 0;
  1285. this.z = 0;
  1286. this.w = 0;
  1287. } else {
  1288. l = 1 / l;
  1289. this.x *= l;
  1290. this.y *= l;
  1291. this.z *= l;
  1292. this.w *= l;
  1293. }
  1294. return this;
  1295. }
  1296. /**
  1297. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  1298. * @author unphased, https://github.com/unphased
  1299. */
  1300. normalizeFast() {
  1301. const f = (3.0 - (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w)) / 2.0;
  1302. if (f === 0) {
  1303. this.x = 0;
  1304. this.y = 0;
  1305. this.z = 0;
  1306. this.w = 0;
  1307. } else {
  1308. this.x *= f;
  1309. this.y *= f;
  1310. this.z *= f;
  1311. this.w *= f;
  1312. }
  1313. return this;
  1314. }
  1315. /**
  1316. * Multiply the quaternion by a vector
  1317. */
  1318. vmult(v, target = new Vec3()) {
  1319. const x = v.x;
  1320. const y = v.y;
  1321. const z = v.z;
  1322. const qx = this.x;
  1323. const qy = this.y;
  1324. const qz = this.z;
  1325. const qw = this.w; // q*v
  1326. const ix = qw * x + qy * z - qz * y;
  1327. const iy = qw * y + qz * x - qx * z;
  1328. const iz = qw * z + qx * y - qy * x;
  1329. const iw = -qx * x - qy * y - qz * z;
  1330. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1331. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1332. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1333. return target;
  1334. }
  1335. /**
  1336. * Copies value of source to this quaternion.
  1337. * @return this
  1338. */
  1339. copy(quat) {
  1340. this.x = quat.x;
  1341. this.y = quat.y;
  1342. this.z = quat.z;
  1343. this.w = quat.w;
  1344. return this;
  1345. }
  1346. /**
  1347. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: https://www.euclideanspace.com/maths/standards/index.htm
  1348. * @param order Three-character string, defaults to "YZX"
  1349. */
  1350. toEuler(target, order = 'YZX') {
  1351. let heading;
  1352. let attitude;
  1353. let bank;
  1354. const x = this.x;
  1355. const y = this.y;
  1356. const z = this.z;
  1357. const w = this.w;
  1358. switch (order) {
  1359. case 'YZX':
  1360. const test = x * y + z * w;
  1361. if (test > 0.499) {
  1362. // singularity at north pole
  1363. heading = 2 * Math.atan2(x, w);
  1364. attitude = Math.PI / 2;
  1365. bank = 0;
  1366. }
  1367. if (test < -0.499) {
  1368. // singularity at south pole
  1369. heading = -2 * Math.atan2(x, w);
  1370. attitude = -Math.PI / 2;
  1371. bank = 0;
  1372. }
  1373. if (heading === undefined) {
  1374. const sqx = x * x;
  1375. const sqy = y * y;
  1376. const sqz = z * z;
  1377. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1378. attitude = Math.asin(2 * test); // attitude
  1379. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1380. }
  1381. break;
  1382. default:
  1383. throw new Error("Euler order " + order + " not supported yet.");
  1384. }
  1385. target.y = heading;
  1386. target.z = attitude;
  1387. target.x = bank;
  1388. }
  1389. /**
  1390. * @param order The order to apply angles: 'XYZ' or 'YXZ' or any other combination.
  1391. *
  1392. * See {@link https://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors MathWorks} reference
  1393. */
  1394. setFromEuler(x, y, z, order = 'XYZ') {
  1395. const c1 = Math.cos(x / 2);
  1396. const c2 = Math.cos(y / 2);
  1397. const c3 = Math.cos(z / 2);
  1398. const s1 = Math.sin(x / 2);
  1399. const s2 = Math.sin(y / 2);
  1400. const s3 = Math.sin(z / 2);
  1401. if (order === 'XYZ') {
  1402. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1403. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1404. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1405. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1406. } else if (order === 'YXZ') {
  1407. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1408. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1409. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1410. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1411. } else if (order === 'ZXY') {
  1412. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1413. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1414. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1415. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1416. } else if (order === 'ZYX') {
  1417. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1418. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1419. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1420. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1421. } else if (order === 'YZX') {
  1422. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  1423. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  1424. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  1425. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  1426. } else if (order === 'XZY') {
  1427. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  1428. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  1429. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  1430. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  1431. }
  1432. return this;
  1433. }
  1434. clone() {
  1435. return new Quaternion(this.x, this.y, this.z, this.w);
  1436. }
  1437. /**
  1438. * Performs a spherical linear interpolation between two quat
  1439. *
  1440. * @param toQuat second operand
  1441. * @param t interpolation amount between the self quaternion and toQuat
  1442. * @param target A quaternion to store the result in. If not provided, a new one will be created.
  1443. * @returns {Quaternion} The "target" object
  1444. */
  1445. slerp(toQuat, t, target = new Quaternion()) {
  1446. const ax = this.x;
  1447. const ay = this.y;
  1448. const az = this.z;
  1449. const aw = this.w;
  1450. let bx = toQuat.x;
  1451. let by = toQuat.y;
  1452. let bz = toQuat.z;
  1453. let bw = toQuat.w;
  1454. let omega;
  1455. let cosom;
  1456. let sinom;
  1457. let scale0;
  1458. let scale1; // calc cosine
  1459. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  1460. if (cosom < 0.0) {
  1461. cosom = -cosom;
  1462. bx = -bx;
  1463. by = -by;
  1464. bz = -bz;
  1465. bw = -bw;
  1466. } // calculate coefficients
  1467. if (1.0 - cosom > 0.000001) {
  1468. // standard case (slerp)
  1469. omega = Math.acos(cosom);
  1470. sinom = Math.sin(omega);
  1471. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  1472. scale1 = Math.sin(t * omega) / sinom;
  1473. } else {
  1474. // "from" and "to" quaternions are very close
  1475. // ... so we can do a linear interpolation
  1476. scale0 = 1.0 - t;
  1477. scale1 = t;
  1478. } // calculate final values
  1479. target.x = scale0 * ax + scale1 * bx;
  1480. target.y = scale0 * ay + scale1 * by;
  1481. target.z = scale0 * az + scale1 * bz;
  1482. target.w = scale0 * aw + scale1 * bw;
  1483. return target;
  1484. }
  1485. /**
  1486. * Rotate an absolute orientation quaternion given an angular velocity and a time step.
  1487. */
  1488. integrate(angularVelocity, dt, angularFactor, target = new Quaternion()) {
  1489. const ax = angularVelocity.x * angularFactor.x,
  1490. ay = angularVelocity.y * angularFactor.y,
  1491. az = angularVelocity.z * angularFactor.z,
  1492. bx = this.x,
  1493. by = this.y,
  1494. bz = this.z,
  1495. bw = this.w;
  1496. const half_dt = dt * 0.5;
  1497. target.x += half_dt * (ax * bw + ay * bz - az * by);
  1498. target.y += half_dt * (ay * bw + az * bx - ax * bz);
  1499. target.z += half_dt * (az * bw + ax * by - ay * bx);
  1500. target.w += half_dt * (-ax * bx - ay * by - az * bz);
  1501. return target;
  1502. }
  1503. }
  1504. const sfv_t1 = new Vec3();
  1505. const sfv_t2 = new Vec3();
  1506. /**
  1507. * The available shape types.
  1508. */
  1509. const SHAPE_TYPES = {
  1510. /** SPHERE */
  1511. SPHERE: 1,
  1512. /** PLANE */
  1513. PLANE: 2,
  1514. /** BOX */
  1515. BOX: 4,
  1516. /** COMPOUND */
  1517. COMPOUND: 8,
  1518. /** CONVEXPOLYHEDRON */
  1519. CONVEXPOLYHEDRON: 16,
  1520. /** HEIGHTFIELD */
  1521. HEIGHTFIELD: 32,
  1522. /** PARTICLE */
  1523. PARTICLE: 64,
  1524. /** CYLINDER */
  1525. CYLINDER: 128,
  1526. /** TRIMESH */
  1527. TRIMESH: 256
  1528. };
  1529. /**
  1530. * ShapeType
  1531. */
  1532. /**
  1533. * Base class for shapes
  1534. */
  1535. class Shape {
  1536. /**
  1537. * Identifier of the Shape.
  1538. */
  1539. /**
  1540. * The type of this shape. Must be set to an int > 0 by subclasses.
  1541. */
  1542. /**
  1543. * The local bounding sphere radius of this shape.
  1544. */
  1545. /**
  1546. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  1547. * @default true
  1548. */
  1549. /**
  1550. * @default 1
  1551. */
  1552. /**
  1553. * @default -1
  1554. */
  1555. /**
  1556. * Optional material of the shape that regulates contact properties.
  1557. */
  1558. /**
  1559. * The body to which the shape is added to.
  1560. */
  1561. /**
  1562. * All the Shape types.
  1563. */
  1564. constructor(options = {}) {
  1565. this.id = void 0;
  1566. this.type = void 0;
  1567. this.boundingSphereRadius = void 0;
  1568. this.collisionResponse = void 0;
  1569. this.collisionFilterGroup = void 0;
  1570. this.collisionFilterMask = void 0;
  1571. this.material = void 0;
  1572. this.body = void 0;
  1573. this.id = Shape.idCounter++;
  1574. this.type = options.type || 0;
  1575. this.boundingSphereRadius = 0;
  1576. this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;
  1577. this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;
  1578. this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;
  1579. this.material = options.material ? options.material : null;
  1580. this.body = null;
  1581. }
  1582. /**
  1583. * Computes the bounding sphere radius.
  1584. * The result is stored in the property `.boundingSphereRadius`
  1585. */
  1586. updateBoundingSphereRadius() {
  1587. throw "computeBoundingSphereRadius() not implemented for shape type " + this.type;
  1588. }
  1589. /**
  1590. * Get the volume of this shape
  1591. */
  1592. volume() {
  1593. throw "volume() not implemented for shape type " + this.type;
  1594. }
  1595. /**
  1596. * Calculates the inertia in the local frame for this shape.
  1597. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  1598. */
  1599. calculateLocalInertia(mass, target) {
  1600. throw "calculateLocalInertia() not implemented for shape type " + this.type;
  1601. }
  1602. /**
  1603. * @todo use abstract for these kind of methods
  1604. */
  1605. calculateWorldAABB(pos, quat, min, max) {
  1606. throw "calculateWorldAABB() not implemented for shape type " + this.type;
  1607. }
  1608. }
  1609. Shape.idCounter = 0;
  1610. Shape.types = SHAPE_TYPES;
  1611. /**
  1612. * Transformation utilities.
  1613. */
  1614. class Transform {
  1615. /**
  1616. * position
  1617. */
  1618. /**
  1619. * quaternion
  1620. */
  1621. constructor(options = {}) {
  1622. this.position = void 0;
  1623. this.quaternion = void 0;
  1624. this.position = new Vec3();
  1625. this.quaternion = new Quaternion();
  1626. if (options.position) {
  1627. this.position.copy(options.position);
  1628. }
  1629. if (options.quaternion) {
  1630. this.quaternion.copy(options.quaternion);
  1631. }
  1632. }
  1633. /**
  1634. * Get a global point in local transform coordinates.
  1635. */
  1636. pointToLocal(worldPoint, result) {
  1637. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  1638. }
  1639. /**
  1640. * Get a local point in global transform coordinates.
  1641. */
  1642. pointToWorld(localPoint, result) {
  1643. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  1644. }
  1645. /**
  1646. * vectorToWorldFrame
  1647. */
  1648. vectorToWorldFrame(localVector, result = new Vec3()) {
  1649. this.quaternion.vmult(localVector, result);
  1650. return result;
  1651. }
  1652. /**
  1653. * pointToLocalFrame
  1654. */
  1655. static pointToLocalFrame(position, quaternion, worldPoint, result = new Vec3()) {
  1656. worldPoint.vsub(position, result);
  1657. quaternion.conjugate(tmpQuat$1);
  1658. tmpQuat$1.vmult(result, result);
  1659. return result;
  1660. }
  1661. /**
  1662. * pointToWorldFrame
  1663. */
  1664. static pointToWorldFrame(position, quaternion, localPoint, result = new Vec3()) {
  1665. quaternion.vmult(localPoint, result);
  1666. result.vadd(position, result);
  1667. return result;
  1668. }
  1669. /**
  1670. * vectorToWorldFrame
  1671. */
  1672. static vectorToWorldFrame(quaternion, localVector, result = new Vec3()) {
  1673. quaternion.vmult(localVector, result);
  1674. return result;
  1675. }
  1676. /**
  1677. * vectorToLocalFrame
  1678. */
  1679. static vectorToLocalFrame(position, quaternion, worldVector, result = new Vec3()) {
  1680. quaternion.w *= -1;
  1681. quaternion.vmult(worldVector, result);
  1682. quaternion.w *= -1;
  1683. return result;
  1684. }
  1685. }
  1686. const tmpQuat$1 = new Quaternion();
  1687. /**
  1688. * A set of polygons describing a convex shape.
  1689. *
  1690. * The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  1691. * in the same 3D plane), instead these should be merged into one polygon.
  1692. *
  1693. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  1694. * @author schteppe / https://github.com/schteppe
  1695. * @see https://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  1696. *
  1697. * @todo Move the clipping functions to ContactGenerator?
  1698. * @todo Automatically merge coplanar polygons in constructor.
  1699. * @example
  1700. * const convexShape = new CANNON.ConvexPolyhedron({ vertices, faces })
  1701. * const convexBody = new CANNON.Body({ mass: 1, shape: convexShape })
  1702. * world.addBody(convexBody)
  1703. */
  1704. class ConvexPolyhedron extends Shape {
  1705. /** vertices */
  1706. /**
  1707. * Array of integer arrays, indicating which vertices each face consists of
  1708. */
  1709. /** faceNormals */
  1710. /** worldVertices */
  1711. /** worldVerticesNeedsUpdate */
  1712. /** worldFaceNormals */
  1713. /** worldFaceNormalsNeedsUpdate */
  1714. /**
  1715. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  1716. */
  1717. /** uniqueEdges */
  1718. /**
  1719. * @param vertices An array of Vec3's
  1720. * @param faces Array of integer arrays, describing which vertices that is included in each face.
  1721. */
  1722. constructor(props = {}) {
  1723. const {
  1724. vertices = [],
  1725. faces = [],
  1726. normals = [],
  1727. axes,
  1728. boundingSphereRadius
  1729. } = props;
  1730. super({
  1731. type: Shape.types.CONVEXPOLYHEDRON
  1732. });
  1733. this.vertices = void 0;
  1734. this.faces = void 0;
  1735. this.faceNormals = void 0;
  1736. this.worldVertices = void 0;
  1737. this.worldVerticesNeedsUpdate = void 0;
  1738. this.worldFaceNormals = void 0;
  1739. this.worldFaceNormalsNeedsUpdate = void 0;
  1740. this.uniqueAxes = void 0;
  1741. this.uniqueEdges = void 0;
  1742. this.vertices = vertices;
  1743. this.faces = faces;
  1744. this.faceNormals = normals;
  1745. if (this.faceNormals.length === 0) {
  1746. this.computeNormals();
  1747. }
  1748. if (!boundingSphereRadius) {
  1749. this.updateBoundingSphereRadius();
  1750. } else {
  1751. this.boundingSphereRadius = boundingSphereRadius;
  1752. }
  1753. this.worldVertices = []; // World transformed version of .vertices
  1754. this.worldVerticesNeedsUpdate = true;
  1755. this.worldFaceNormals = []; // World transformed version of .faceNormals
  1756. this.worldFaceNormalsNeedsUpdate = true;
  1757. this.uniqueAxes = axes ? axes.slice() : null;
  1758. this.uniqueEdges = [];
  1759. this.computeEdges();
  1760. }
  1761. /**
  1762. * Computes uniqueEdges
  1763. */
  1764. computeEdges() {
  1765. const faces = this.faces;
  1766. const vertices = this.vertices;
  1767. const edges = this.uniqueEdges;
  1768. edges.length = 0;
  1769. const edge = new Vec3();
  1770. for (let i = 0; i !== faces.length; i++) {
  1771. const face = faces[i];
  1772. const numVertices = face.length;
  1773. for (let j = 0; j !== numVertices; j++) {
  1774. const k = (j + 1) % numVertices;
  1775. vertices[face[j]].vsub(vertices[face[k]], edge);
  1776. edge.normalize();
  1777. let found = false;
  1778. for (let p = 0; p !== edges.length; p++) {
  1779. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)) {
  1780. found = true;
  1781. break;
  1782. }
  1783. }
  1784. if (!found) {
  1785. edges.push(edge.clone());
  1786. }
  1787. }
  1788. }
  1789. }
  1790. /**
  1791. * Compute the normals of the faces.
  1792. * Will reuse existing Vec3 objects in the `faceNormals` array if they exist.
  1793. */
  1794. computeNormals() {
  1795. this.faceNormals.length = this.faces.length; // Generate normals
  1796. for (let i = 0; i < this.faces.length; i++) {
  1797. // Check so all vertices exists for this face
  1798. for (let j = 0; j < this.faces[i].length; j++) {
  1799. if (!this.vertices[this.faces[i][j]]) {
  1800. throw new Error("Vertex " + this.faces[i][j] + " not found!");
  1801. }
  1802. }
  1803. const n = this.faceNormals[i] || new Vec3();
  1804. this.getFaceNormal(i, n);
  1805. n.negate(n);
  1806. this.faceNormals[i] = n;
  1807. const vertex = this.vertices[this.faces[i][0]];
  1808. if (n.dot(vertex) < 0) {
  1809. console.error(".faceNormals[" + i + "] = Vec3(" + n.toString() + ") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");
  1810. for (let j = 0; j < this.faces[i].length; j++) {
  1811. console.warn(".vertices[" + this.faces[i][j] + "] = Vec3(" + this.vertices[this.faces[i][j]].toString() + ")");
  1812. }
  1813. }
  1814. }
  1815. }
  1816. /**
  1817. * Compute the normal of a face from its vertices
  1818. */
  1819. getFaceNormal(i, target) {
  1820. const f = this.faces[i];
  1821. const va = this.vertices[f[0]];
  1822. const vb = this.vertices[f[1]];
  1823. const vc = this.vertices[f[2]];
  1824. ConvexPolyhedron.computeNormal(va, vb, vc, target);
  1825. }
  1826. /**
  1827. * Get face normal given 3 vertices
  1828. */
  1829. static computeNormal(va, vb, vc, target) {
  1830. const cb = new Vec3();
  1831. const ab = new Vec3();
  1832. vb.vsub(va, ab);
  1833. vc.vsub(vb, cb);
  1834. cb.cross(ab, target);
  1835. if (!target.isZero()) {
  1836. target.normalize();
  1837. }
  1838. }
  1839. /**
  1840. * @param minDist Clamp distance
  1841. * @param result The an array of contact point objects, see clipFaceAgainstHull
  1842. */
  1843. clipAgainstHull(posA, quatA, hullB, posB, quatB, separatingNormal, minDist, maxDist, result) {
  1844. const WorldNormal = new Vec3();
  1845. let closestFaceB = -1;
  1846. let dmax = -Number.MAX_VALUE;
  1847. for (let face = 0; face < hullB.faces.length; face++) {
  1848. WorldNormal.copy(hullB.faceNormals[face]);
  1849. quatB.vmult(WorldNormal, WorldNormal);
  1850. const d = WorldNormal.dot(separatingNormal);
  1851. if (d > dmax) {
  1852. dmax = d;
  1853. closestFaceB = face;
  1854. }
  1855. }
  1856. const worldVertsB1 = [];
  1857. for (let i = 0; i < hullB.faces[closestFaceB].length; i++) {
  1858. const b = hullB.vertices[hullB.faces[closestFaceB][i]];
  1859. const worldb = new Vec3();
  1860. worldb.copy(b);
  1861. quatB.vmult(worldb, worldb);
  1862. posB.vadd(worldb, worldb);
  1863. worldVertsB1.push(worldb);
  1864. }
  1865. if (closestFaceB >= 0) {
  1866. this.clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result);
  1867. }
  1868. }
  1869. /**
  1870. * Find the separating axis between this hull and another
  1871. * @param target The target vector to save the axis in
  1872. * @return Returns false if a separation is found, else true
  1873. */
  1874. findSeparatingAxis(hullB, posA, quatA, posB, quatB, target, faceListA, faceListB) {
  1875. const faceANormalWS3 = new Vec3();
  1876. const Worldnormal1 = new Vec3();
  1877. const deltaC = new Vec3();
  1878. const worldEdge0 = new Vec3();
  1879. const worldEdge1 = new Vec3();
  1880. const Cross = new Vec3();
  1881. let dmin = Number.MAX_VALUE;
  1882. const hullA = this;
  1883. if (!hullA.uniqueAxes) {
  1884. const numFacesA = faceListA ? faceListA.length : hullA.faces.length; // Test face normals from hullA
  1885. for (let i = 0; i < numFacesA; i++) {
  1886. const fi = faceListA ? faceListA[i] : i; // Get world face normal
  1887. faceANormalWS3.copy(hullA.faceNormals[fi]);
  1888. quatA.vmult(faceANormalWS3, faceANormalWS3);
  1889. const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  1890. if (d === false) {
  1891. return false;
  1892. }
  1893. if (d < dmin) {
  1894. dmin = d;
  1895. target.copy(faceANormalWS3);
  1896. }
  1897. }
  1898. } else {
  1899. // Test unique axes
  1900. for (let i = 0; i !== hullA.uniqueAxes.length; i++) {
  1901. // Get world axis
  1902. quatA.vmult(hullA.uniqueAxes[i], faceANormalWS3);
  1903. const d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  1904. if (d === false) {
  1905. return false;
  1906. }
  1907. if (d < dmin) {
  1908. dmin = d;
  1909. target.copy(faceANormalWS3);
  1910. }
  1911. }
  1912. }
  1913. if (!hullB.uniqueAxes) {
  1914. // Test face normals from hullB
  1915. const numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  1916. for (let i = 0; i < numFacesB; i++) {
  1917. const fi = faceListB ? faceListB[i] : i;
  1918. Worldnormal1.copy(hullB.faceNormals[fi]);
  1919. quatB.vmult(Worldnormal1, Worldnormal1);
  1920. const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);
  1921. if (d === false) {
  1922. return false;
  1923. }
  1924. if (d < dmin) {
  1925. dmin = d;
  1926. target.copy(Worldnormal1);
  1927. }
  1928. }
  1929. } else {
  1930. // Test unique axes in B
  1931. for (let i = 0; i !== hullB.uniqueAxes.length; i++) {
  1932. quatB.vmult(hullB.uniqueAxes[i], Worldnormal1);
  1933. const d = hullA.testSepAxis(Worldnormal1, hullB, posA, quatA, posB, quatB);
  1934. if (d === false) {
  1935. return false;
  1936. }
  1937. if (d < dmin) {
  1938. dmin = d;
  1939. target.copy(Worldnormal1);
  1940. }
  1941. }
  1942. } // Test edges
  1943. for (let e0 = 0; e0 !== hullA.uniqueEdges.length; e0++) {
  1944. // Get world edge
  1945. quatA.vmult(hullA.uniqueEdges[e0], worldEdge0);
  1946. for (let e1 = 0; e1 !== hullB.uniqueEdges.length; e1++) {
  1947. // Get world edge 2
  1948. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  1949. worldEdge0.cross(worldEdge1, Cross);
  1950. if (!Cross.almostZero()) {
  1951. Cross.normalize();
  1952. const dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  1953. if (dist === false) {
  1954. return false;
  1955. }
  1956. if (dist < dmin) {
  1957. dmin = dist;
  1958. target.copy(Cross);
  1959. }
  1960. }
  1961. }
  1962. }
  1963. posB.vsub(posA, deltaC);
  1964. if (deltaC.dot(target) > 0.0) {
  1965. target.negate(target);
  1966. }
  1967. return true;
  1968. }
  1969. /**
  1970. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  1971. * @return The overlap depth, or FALSE if no penetration.
  1972. */
  1973. testSepAxis(axis, hullB, posA, quatA, posB, quatB) {
  1974. const hullA = this;
  1975. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  1976. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  1977. const maxA = maxminA[0];
  1978. const minA = maxminA[1];
  1979. const maxB = maxminB[0];
  1980. const minB = maxminB[1];
  1981. if (maxA < minB || maxB < minA) {
  1982. return false; // Separated
  1983. }
  1984. const d0 = maxA - minB;
  1985. const d1 = maxB - minA;
  1986. const depth = d0 < d1 ? d0 : d1;
  1987. return depth;
  1988. }
  1989. /**
  1990. * calculateLocalInertia
  1991. */
  1992. calculateLocalInertia(mass, target) {
  1993. // Approximate with box inertia
  1994. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  1995. const aabbmax = new Vec3();
  1996. const aabbmin = new Vec3();
  1997. this.computeLocalAABB(aabbmin, aabbmax);
  1998. const x = aabbmax.x - aabbmin.x;
  1999. const y = aabbmax.y - aabbmin.y;
  2000. const z = aabbmax.z - aabbmin.z;
  2001. target.x = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z);
  2002. target.y = 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z);
  2003. target.z = 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x);
  2004. }
  2005. /**
  2006. * @param face_i Index of the face
  2007. */
  2008. getPlaneConstantOfFace(face_i) {
  2009. const f = this.faces[face_i];
  2010. const n = this.faceNormals[face_i];
  2011. const v = this.vertices[f[0]];
  2012. const c = -n.dot(v);
  2013. return c;
  2014. }
  2015. /**
  2016. * Clip a face against a hull.
  2017. * @param worldVertsB1 An array of Vec3 with vertices in the world frame.
  2018. * @param minDist Distance clamping
  2019. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  2020. */
  2021. clipFaceAgainstHull(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist, result) {
  2022. const faceANormalWS = new Vec3();
  2023. const edge0 = new Vec3();
  2024. const WorldEdge0 = new Vec3();
  2025. const worldPlaneAnormal1 = new Vec3();
  2026. const planeNormalWS1 = new Vec3();
  2027. const worldA1 = new Vec3();
  2028. const localPlaneNormal = new Vec3();
  2029. const planeNormalWS = new Vec3();
  2030. const hullA = this;
  2031. const worldVertsB2 = [];
  2032. const pVtxIn = worldVertsB1;
  2033. const pVtxOut = worldVertsB2;
  2034. let closestFaceA = -1;
  2035. let dmin = Number.MAX_VALUE; // Find the face with normal closest to the separating axis
  2036. for (let face = 0; face < hullA.faces.length; face++) {
  2037. faceANormalWS.copy(hullA.faceNormals[face]);
  2038. quatA.vmult(faceANormalWS, faceANormalWS);
  2039. const d = faceANormalWS.dot(separatingNormal);
  2040. if (d < dmin) {
  2041. dmin = d;
  2042. closestFaceA = face;
  2043. }
  2044. }
  2045. if (closestFaceA < 0) {
  2046. return;
  2047. } // Get the face and construct connected faces
  2048. const polyA = hullA.faces[closestFaceA];
  2049. polyA.connectedFaces = [];
  2050. for (let i = 0; i < hullA.faces.length; i++) {
  2051. for (let j = 0; j < hullA.faces[i].length; j++) {
  2052. if (
  2053. /* Sharing a vertex*/
  2054. polyA.indexOf(hullA.faces[i][j]) !== -1 &&
  2055. /* Not the one we are looking for connections from */
  2056. i !== closestFaceA &&
  2057. /* Not already added */
  2058. polyA.connectedFaces.indexOf(i) === -1) {
  2059. polyA.connectedFaces.push(i);
  2060. }
  2061. }
  2062. } // Clip the polygon to the back of the planes of all faces of hull A,
  2063. // that are adjacent to the witness face
  2064. const numVerticesA = polyA.length;
  2065. for (let i = 0; i < numVerticesA; i++) {
  2066. const a = hullA.vertices[polyA[i]];
  2067. const b = hullA.vertices[polyA[(i + 1) % numVerticesA]];
  2068. a.vsub(b, edge0);
  2069. WorldEdge0.copy(edge0);
  2070. quatA.vmult(WorldEdge0, WorldEdge0);
  2071. posA.vadd(WorldEdge0, WorldEdge0);
  2072. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);
  2073. quatA.vmult(worldPlaneAnormal1, worldPlaneAnormal1);
  2074. posA.vadd(worldPlaneAnormal1, worldPlaneAnormal1);
  2075. WorldEdge0.cross(worldPlaneAnormal1, planeNormalWS1);
  2076. planeNormalWS1.negate(planeNormalWS1);
  2077. worldA1.copy(a);
  2078. quatA.vmult(worldA1, worldA1);
  2079. posA.vadd(worldA1, worldA1);
  2080. const otherFace = polyA.connectedFaces[i];
  2081. localPlaneNormal.copy(this.faceNormals[otherFace]);
  2082. const localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  2083. planeNormalWS.copy(localPlaneNormal);
  2084. quatA.vmult(planeNormalWS, planeNormalWS);
  2085. const planeEqWS = localPlaneEq - planeNormalWS.dot(posA); // Clip face against our constructed plane
  2086. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS); // Throw away all clipped points, but save the remaining until next clip
  2087. while (pVtxIn.length) {
  2088. pVtxIn.shift();
  2089. }
  2090. while (pVtxOut.length) {
  2091. pVtxIn.push(pVtxOut.shift());
  2092. }
  2093. } // only keep contact points that are behind the witness face
  2094. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  2095. const localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  2096. planeNormalWS.copy(localPlaneNormal);
  2097. quatA.vmult(planeNormalWS, planeNormalWS);
  2098. const planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  2099. for (let i = 0; i < pVtxIn.length; i++) {
  2100. let depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; // ???
  2101. if (depth <= minDist) {
  2102. console.log("clamped: depth=" + depth + " to minDist=" + minDist);
  2103. depth = minDist;
  2104. }
  2105. if (depth <= maxDist) {
  2106. const point = pVtxIn[i];
  2107. if (depth <= 1e-6) {
  2108. const p = {
  2109. point,
  2110. normal: planeNormalWS,
  2111. depth
  2112. };
  2113. result.push(p);
  2114. }
  2115. }
  2116. }
  2117. }
  2118. /**
  2119. * Clip a face in a hull against the back of a plane.
  2120. * @param planeConstant The constant in the mathematical plane equation
  2121. */
  2122. clipFaceAgainstPlane(inVertices, outVertices, planeNormal, planeConstant) {
  2123. let n_dot_first;
  2124. let n_dot_last;
  2125. const numVerts = inVertices.length;
  2126. if (numVerts < 2) {
  2127. return outVertices;
  2128. }
  2129. let firstVertex = inVertices[inVertices.length - 1];
  2130. let lastVertex = inVertices[0];
  2131. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  2132. for (let vi = 0; vi < numVerts; vi++) {
  2133. lastVertex = inVertices[vi];
  2134. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  2135. if (n_dot_first < 0) {
  2136. if (n_dot_last < 0) {
  2137. // Start < 0, end < 0, so output lastVertex
  2138. const newv = new Vec3();
  2139. newv.copy(lastVertex);
  2140. outVertices.push(newv);
  2141. } else {
  2142. // Start < 0, end >= 0, so output intersection
  2143. const newv = new Vec3();
  2144. firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
  2145. outVertices.push(newv);
  2146. }
  2147. } else {
  2148. if (n_dot_last < 0) {
  2149. // Start >= 0, end < 0 so output intersection and end
  2150. const newv = new Vec3();
  2151. firstVertex.lerp(lastVertex, n_dot_first / (n_dot_first - n_dot_last), newv);
  2152. outVertices.push(newv);
  2153. outVertices.push(lastVertex);
  2154. }
  2155. }
  2156. firstVertex = lastVertex;
  2157. n_dot_first = n_dot_last;
  2158. }
  2159. return outVertices;
  2160. }
  2161. /**
  2162. * Updates `.worldVertices` and sets `.worldVerticesNeedsUpdate` to false.
  2163. */
  2164. computeWorldVertices(position, quat) {
  2165. while (this.worldVertices.length < this.vertices.length) {
  2166. this.worldVertices.push(new Vec3());
  2167. }
  2168. const verts = this.vertices;
  2169. const worldVerts = this.worldVertices;
  2170. for (let i = 0; i !== this.vertices.length; i++) {
  2171. quat.vmult(verts[i], worldVerts[i]);
  2172. position.vadd(worldVerts[i], worldVerts[i]);
  2173. }
  2174. this.worldVerticesNeedsUpdate = false;
  2175. }
  2176. computeLocalAABB(aabbmin, aabbmax) {
  2177. const vertices = this.vertices;
  2178. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2179. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2180. for (let i = 0; i < this.vertices.length; i++) {
  2181. const v = vertices[i];
  2182. if (v.x < aabbmin.x) {
  2183. aabbmin.x = v.x;
  2184. } else if (v.x > aabbmax.x) {
  2185. aabbmax.x = v.x;
  2186. }
  2187. if (v.y < aabbmin.y) {
  2188. aabbmin.y = v.y;
  2189. } else if (v.y > aabbmax.y) {
  2190. aabbmax.y = v.y;
  2191. }
  2192. if (v.z < aabbmin.z) {
  2193. aabbmin.z = v.z;
  2194. } else if (v.z > aabbmax.z) {
  2195. aabbmax.z = v.z;
  2196. }
  2197. }
  2198. }
  2199. /**
  2200. * Updates `worldVertices` and sets `worldVerticesNeedsUpdate` to false.
  2201. */
  2202. computeWorldFaceNormals(quat) {
  2203. const N = this.faceNormals.length;
  2204. while (this.worldFaceNormals.length < N) {
  2205. this.worldFaceNormals.push(new Vec3());
  2206. }
  2207. const normals = this.faceNormals;
  2208. const worldNormals = this.worldFaceNormals;
  2209. for (let i = 0; i !== N; i++) {
  2210. quat.vmult(normals[i], worldNormals[i]);
  2211. }
  2212. this.worldFaceNormalsNeedsUpdate = false;
  2213. }
  2214. /**
  2215. * updateBoundingSphereRadius
  2216. */
  2217. updateBoundingSphereRadius() {
  2218. // Assume points are distributed with local (0,0,0) as center
  2219. let max2 = 0;
  2220. const verts = this.vertices;
  2221. for (let i = 0; i !== verts.length; i++) {
  2222. const norm2 = verts[i].lengthSquared();
  2223. if (norm2 > max2) {
  2224. max2 = norm2;
  2225. }
  2226. }
  2227. this.boundingSphereRadius = Math.sqrt(max2);
  2228. }
  2229. /**
  2230. * calculateWorldAABB
  2231. */
  2232. calculateWorldAABB(pos, quat, min, max) {
  2233. const verts = this.vertices;
  2234. let minx;
  2235. let miny;
  2236. let minz;
  2237. let maxx;
  2238. let maxy;
  2239. let maxz;
  2240. let tempWorldVertex = new Vec3();
  2241. for (let i = 0; i < verts.length; i++) {
  2242. tempWorldVertex.copy(verts[i]);
  2243. quat.vmult(tempWorldVertex, tempWorldVertex);
  2244. pos.vadd(tempWorldVertex, tempWorldVertex);
  2245. const v = tempWorldVertex;
  2246. if (minx === undefined || v.x < minx) {
  2247. minx = v.x;
  2248. }
  2249. if (maxx === undefined || v.x > maxx) {
  2250. maxx = v.x;
  2251. }
  2252. if (miny === undefined || v.y < miny) {
  2253. miny = v.y;
  2254. }
  2255. if (maxy === undefined || v.y > maxy) {
  2256. maxy = v.y;
  2257. }
  2258. if (minz === undefined || v.z < minz) {
  2259. minz = v.z;
  2260. }
  2261. if (maxz === undefined || v.z > maxz) {
  2262. maxz = v.z;
  2263. }
  2264. }
  2265. min.set(minx, miny, minz);
  2266. max.set(maxx, maxy, maxz);
  2267. }
  2268. /**
  2269. * Get approximate convex volume
  2270. */
  2271. volume() {
  2272. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  2273. }
  2274. /**
  2275. * Get an average of all the vertices positions
  2276. */
  2277. getAveragePointLocal(target = new Vec3()) {
  2278. const verts = this.vertices;
  2279. for (let i = 0; i < verts.length; i++) {
  2280. target.vadd(verts[i], target);
  2281. }
  2282. target.scale(1 / verts.length, target);
  2283. return target;
  2284. }
  2285. /**
  2286. * Transform all local points. Will change the .vertices
  2287. */
  2288. transformAllPoints(offset, quat) {
  2289. const n = this.vertices.length;
  2290. const verts = this.vertices; // Apply rotation
  2291. if (quat) {
  2292. // Rotate vertices
  2293. for (let i = 0; i < n; i++) {
  2294. const v = verts[i];
  2295. quat.vmult(v, v);
  2296. } // Rotate face normals
  2297. for (let i = 0; i < this.faceNormals.length; i++) {
  2298. const v = this.faceNormals[i];
  2299. quat.vmult(v, v);
  2300. }
  2301. /*
  2302. // Rotate edges
  2303. for(let i=0; i<this.uniqueEdges.length; i++){
  2304. const v = this.uniqueEdges[i];
  2305. quat.vmult(v,v);
  2306. }*/
  2307. } // Apply offset
  2308. if (offset) {
  2309. for (let i = 0; i < n; i++) {
  2310. const v = verts[i];
  2311. v.vadd(offset, v);
  2312. }
  2313. }
  2314. }
  2315. /**
  2316. * Checks whether p is inside the polyhedra. Must be in local coords.
  2317. * The point lies outside of the convex hull of the other points if and only if the direction
  2318. * of all the vectors from it to those other points are on less than one half of a sphere around it.
  2319. * @param p A point given in local coordinates
  2320. */
  2321. pointIsInside(p) {
  2322. const verts = this.vertices;
  2323. const faces = this.faces;
  2324. const normals = this.faceNormals;
  2325. const pointInside = new Vec3();
  2326. this.getAveragePointLocal(pointInside);
  2327. for (let i = 0; i < this.faces.length; i++) {
  2328. let n = normals[i];
  2329. const v = verts[faces[i][0]]; // We only need one point in the face
  2330. // This dot product determines which side of the edge the point is
  2331. const vToP = new Vec3();
  2332. p.vsub(v, vToP);
  2333. const r1 = n.dot(vToP);
  2334. const vToPointInside = new Vec3();
  2335. pointInside.vsub(v, vToPointInside);
  2336. const r2 = n.dot(vToPointInside);
  2337. if (r1 < 0 && r2 > 0 || r1 > 0 && r2 < 0) {
  2338. return false; // Encountered some other sign. Exit.
  2339. }
  2340. } // If we got here, all dot products were of the same sign.
  2341. return -1;
  2342. }
  2343. /**
  2344. * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis.
  2345. * Results are saved in the array maxmin.
  2346. * @param result result[0] and result[1] will be set to maximum and minimum, respectively.
  2347. */
  2348. static project(shape, axis, pos, quat, result) {
  2349. const n = shape.vertices.length;
  2350. const localAxis = project_localAxis;
  2351. let max = 0;
  2352. let min = 0;
  2353. const localOrigin = project_localOrigin;
  2354. const vs = shape.vertices;
  2355. localOrigin.setZero(); // Transform the axis to local
  2356. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  2357. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  2358. const add = localOrigin.dot(localAxis);
  2359. min = max = vs[0].dot(localAxis);
  2360. for (let i = 1; i < n; i++) {
  2361. const val = vs[i].dot(localAxis);
  2362. if (val > max) {
  2363. max = val;
  2364. }
  2365. if (val < min) {
  2366. min = val;
  2367. }
  2368. }
  2369. min -= add;
  2370. max -= add;
  2371. if (min > max) {
  2372. // Inconsistent - swap
  2373. const temp = min;
  2374. min = max;
  2375. max = temp;
  2376. } // Output
  2377. result[0] = max;
  2378. result[1] = min;
  2379. }
  2380. }
  2381. const maxminA = [];
  2382. const maxminB = [];
  2383. const project_localAxis = new Vec3();
  2384. const project_localOrigin = new Vec3();
  2385. /**
  2386. * A 3d box shape.
  2387. * @example
  2388. * const size = 1
  2389. * const halfExtents = new CANNON.Vec3(size, size, size)
  2390. * const boxShape = new CANNON.Box(halfExtents)
  2391. * const boxBody = new CANNON.Body({ mass: 1, shape: boxShape })
  2392. * world.addBody(boxBody)
  2393. */
  2394. class Box extends Shape {
  2395. /**
  2396. * The half extents of the box.
  2397. */
  2398. /**
  2399. * Used by the contact generator to make contacts with other convex polyhedra for example.
  2400. */
  2401. constructor(halfExtents) {
  2402. super({
  2403. type: Shape.types.BOX
  2404. });
  2405. this.halfExtents = void 0;
  2406. this.convexPolyhedronRepresentation = void 0;
  2407. this.halfExtents = halfExtents;
  2408. this.convexPolyhedronRepresentation = null;
  2409. this.updateConvexPolyhedronRepresentation();
  2410. this.updateBoundingSphereRadius();
  2411. }
  2412. /**
  2413. * Updates the local convex polyhedron representation used for some collisions.
  2414. */
  2415. updateConvexPolyhedronRepresentation() {
  2416. const sx = this.halfExtents.x;
  2417. const sy = this.halfExtents.y;
  2418. const sz = this.halfExtents.z;
  2419. const V = Vec3;
  2420. const vertices = [new V(-sx, -sy, -sz), new V(sx, -sy, -sz), new V(sx, sy, -sz), new V(-sx, sy, -sz), new V(-sx, -sy, sz), new V(sx, -sy, sz), new V(sx, sy, sz), new V(-sx, sy, sz)];
  2421. const faces = [[3, 2, 1, 0], // -z
  2422. [4, 5, 6, 7], // +z
  2423. [5, 4, 0, 1], // -y
  2424. [2, 3, 7, 6], // +y
  2425. [0, 4, 7, 3], // -x
  2426. [1, 2, 6, 5] // +x
  2427. ];
  2428. const axes = [new V(0, 0, 1), new V(0, 1, 0), new V(1, 0, 0)];
  2429. const h = new ConvexPolyhedron({
  2430. vertices,
  2431. faces,
  2432. axes
  2433. });
  2434. this.convexPolyhedronRepresentation = h;
  2435. h.material = this.material;
  2436. }
  2437. /**
  2438. * Calculate the inertia of the box.
  2439. */
  2440. calculateLocalInertia(mass, target = new Vec3()) {
  2441. Box.calculateInertia(this.halfExtents, mass, target);
  2442. return target;
  2443. }
  2444. static calculateInertia(halfExtents, mass, target) {
  2445. const e = halfExtents;
  2446. target.x = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.z * 2 * e.z);
  2447. target.y = 1.0 / 12.0 * mass * (2 * e.x * 2 * e.x + 2 * e.z * 2 * e.z);
  2448. target.z = 1.0 / 12.0 * mass * (2 * e.y * 2 * e.y + 2 * e.x * 2 * e.x);
  2449. }
  2450. /**
  2451. * Get the box 6 side normals
  2452. * @param sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  2453. * @param quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  2454. */
  2455. getSideNormals(sixTargetVectors, quat) {
  2456. const sides = sixTargetVectors;
  2457. const ex = this.halfExtents;
  2458. sides[0].set(ex.x, 0, 0);
  2459. sides[1].set(0, ex.y, 0);
  2460. sides[2].set(0, 0, ex.z);
  2461. sides[3].set(-ex.x, 0, 0);
  2462. sides[4].set(0, -ex.y, 0);
  2463. sides[5].set(0, 0, -ex.z);
  2464. if (quat !== undefined) {
  2465. for (let i = 0; i !== sides.length; i++) {
  2466. quat.vmult(sides[i], sides[i]);
  2467. }
  2468. }
  2469. return sides;
  2470. }
  2471. /**
  2472. * Returns the volume of the box.
  2473. */
  2474. volume() {
  2475. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  2476. }
  2477. /**
  2478. * updateBoundingSphereRadius
  2479. */
  2480. updateBoundingSphereRadius() {
  2481. this.boundingSphereRadius = this.halfExtents.length();
  2482. }
  2483. /**
  2484. * forEachWorldCorner
  2485. */
  2486. forEachWorldCorner(pos, quat, callback) {
  2487. const e = this.halfExtents;
  2488. const corners = [[e.x, e.y, e.z], [-e.x, e.y, e.z], [-e.x, -e.y, e.z], [-e.x, -e.y, -e.z], [e.x, -e.y, -e.z], [e.x, e.y, -e.z], [-e.x, e.y, -e.z], [e.x, -e.y, e.z]];
  2489. for (let i = 0; i < corners.length; i++) {
  2490. worldCornerTempPos.set(corners[i][0], corners[i][1], corners[i][2]);
  2491. quat.vmult(worldCornerTempPos, worldCornerTempPos);
  2492. pos.vadd(worldCornerTempPos, worldCornerTempPos);
  2493. callback(worldCornerTempPos.x, worldCornerTempPos.y, worldCornerTempPos.z);
  2494. }
  2495. }
  2496. /**
  2497. * calculateWorldAABB
  2498. */
  2499. calculateWorldAABB(pos, quat, min, max) {
  2500. const e = this.halfExtents;
  2501. worldCornersTemp[0].set(e.x, e.y, e.z);
  2502. worldCornersTemp[1].set(-e.x, e.y, e.z);
  2503. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  2504. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  2505. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  2506. worldCornersTemp[5].set(e.x, e.y, -e.z);
  2507. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  2508. worldCornersTemp[7].set(e.x, -e.y, e.z);
  2509. const wc = worldCornersTemp[0];
  2510. quat.vmult(wc, wc);
  2511. pos.vadd(wc, wc);
  2512. max.copy(wc);
  2513. min.copy(wc);
  2514. for (let i = 1; i < 8; i++) {
  2515. const wc = worldCornersTemp[i];
  2516. quat.vmult(wc, wc);
  2517. pos.vadd(wc, wc);
  2518. const x = wc.x;
  2519. const y = wc.y;
  2520. const z = wc.z;
  2521. if (x > max.x) {
  2522. max.x = x;
  2523. }
  2524. if (y > max.y) {
  2525. max.y = y;
  2526. }
  2527. if (z > max.z) {
  2528. max.z = z;
  2529. }
  2530. if (x < min.x) {
  2531. min.x = x;
  2532. }
  2533. if (y < min.y) {
  2534. min.y = y;
  2535. }
  2536. if (z < min.z) {
  2537. min.z = z;
  2538. }
  2539. } // Get each axis max
  2540. // min.set(Infinity,Infinity,Infinity);
  2541. // max.set(-Infinity,-Infinity,-Infinity);
  2542. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  2543. // if(x > max.x){
  2544. // max.x = x;
  2545. // }
  2546. // if(y > max.y){
  2547. // max.y = y;
  2548. // }
  2549. // if(z > max.z){
  2550. // max.z = z;
  2551. // }
  2552. // if(x < min.x){
  2553. // min.x = x;
  2554. // }
  2555. // if(y < min.y){
  2556. // min.y = y;
  2557. // }
  2558. // if(z < min.z){
  2559. // min.z = z;
  2560. // }
  2561. // });
  2562. }
  2563. }
  2564. const worldCornerTempPos = new Vec3();
  2565. const worldCornersTemp = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  2566. /**
  2567. * BODY_TYPES
  2568. */
  2569. const BODY_TYPES = {
  2570. /** DYNAMIC */
  2571. DYNAMIC: 1,
  2572. /** STATIC */
  2573. STATIC: 2,
  2574. /** KINEMATIC */
  2575. KINEMATIC: 4
  2576. };
  2577. /**
  2578. * BodyType
  2579. */
  2580. /**
  2581. * BODY_SLEEP_STATES
  2582. */
  2583. const BODY_SLEEP_STATES = {
  2584. /** AWAKE */
  2585. AWAKE: 0,
  2586. /** SLEEPY */
  2587. SLEEPY: 1,
  2588. /** SLEEPING */
  2589. SLEEPING: 2
  2590. };
  2591. /**
  2592. * BodySleepState
  2593. */
  2594. /**
  2595. * Base class for all body types.
  2596. * @example
  2597. * const shape = new CANNON.Sphere(1)
  2598. * const body = new CANNON.Body({
  2599. * mass: 1,
  2600. * shape,
  2601. * })
  2602. * world.addBody(body)
  2603. */
  2604. class Body extends EventTarget {
  2605. /**
  2606. * Dispatched after two bodies collide. This event is dispatched on each
  2607. * of the two bodies involved in the collision.
  2608. * @event collide
  2609. * @param body The body that was involved in the collision.
  2610. * @param contact The details of the collision.
  2611. */
  2612. /**
  2613. * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
  2614. */
  2615. /**
  2616. * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
  2617. */
  2618. /**
  2619. * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
  2620. */
  2621. /**
  2622. * AWAKE
  2623. */
  2624. /**
  2625. * SLEEPY
  2626. */
  2627. /**
  2628. * SLEEPING
  2629. */
  2630. /**
  2631. * Dispatched after a sleeping body has woken up.
  2632. * @event wakeup
  2633. */
  2634. /**
  2635. * Dispatched after a body has gone in to the sleepy state.
  2636. * @event sleepy
  2637. */
  2638. /**
  2639. * Dispatched after a body has fallen asleep.
  2640. * @event sleep
  2641. */
  2642. /**
  2643. * Identifier of the body.
  2644. */
  2645. /**
  2646. * Position of body in World.bodies. Updated by World and used in ArrayCollisionMatrix.
  2647. */
  2648. /**
  2649. * Reference to the world the body is living in.
  2650. */
  2651. /**
  2652. * Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object. Deprecated - use World events instead.
  2653. * @deprecated Use World events instead
  2654. */
  2655. /**
  2656. * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object. Deprecated - use World events instead.
  2657. * @deprecated Use World events instead
  2658. */
  2659. /**
  2660. * The collision group the body belongs to.
  2661. * @default 1
  2662. */
  2663. /**
  2664. * The collision group the body can collide with.
  2665. * @default -1
  2666. */
  2667. /**
  2668. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled - i.e. "collide" events will be raised, but forces will not be altered.
  2669. */
  2670. /**
  2671. * World space position of the body.
  2672. */
  2673. /**
  2674. * Interpolated position of the body.
  2675. */
  2676. /**
  2677. * Initial position of the body.
  2678. */
  2679. /**
  2680. * World space velocity of the body.
  2681. */
  2682. /**
  2683. * Initial velocity of the body.
  2684. */
  2685. /**
  2686. * Linear force on the body in world space.
  2687. */
  2688. /**
  2689. * The mass of the body.
  2690. * @default 0
  2691. */
  2692. /**
  2693. * The physics material of the body. It defines the body interaction with other bodies.
  2694. */
  2695. /**
  2696. * How much to damp the body velocity each step. It can go from 0 to 1.
  2697. * @default 0.01
  2698. */
  2699. /**
  2700. * One of: `Body.DYNAMIC`, `Body.STATIC` and `Body.KINEMATIC`.
  2701. */
  2702. /**
  2703. * If true, the body will automatically fall to sleep.
  2704. * @default true
  2705. */
  2706. /**
  2707. * Current sleep state.
  2708. */
  2709. /**
  2710. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  2711. * @default 0.1
  2712. */
  2713. /**
  2714. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  2715. * @default 1
  2716. */
  2717. /**
  2718. * World space rotational force on the body, around center of mass.
  2719. */
  2720. /**
  2721. * World space orientation of the body.
  2722. */
  2723. /**
  2724. * Initial quaternion of the body.
  2725. */
  2726. /**
  2727. * Interpolated orientation of the body.
  2728. */
  2729. /**
  2730. * Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
  2731. */
  2732. /**
  2733. * Initial angular velocity of the body.
  2734. */
  2735. /**
  2736. * List of Shapes that have been added to the body.
  2737. */
  2738. /**
  2739. * Position of each Shape in the body, given in local Body space.
  2740. */
  2741. /**
  2742. * Orientation of each Shape, given in local Body space.
  2743. */
  2744. /**
  2745. * The inertia of the body.
  2746. */
  2747. /**
  2748. * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() if you change this after the body creation.
  2749. * @default false
  2750. */
  2751. /**
  2752. * How much to damp the body angular velocity each step. It can go from 0 to 1.
  2753. * @default 0.01
  2754. */
  2755. /**
  2756. * Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
  2757. */
  2758. /**
  2759. * Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
  2760. */
  2761. /**
  2762. * World space bounding box of the body and its shapes.
  2763. */
  2764. /**
  2765. * Indicates if the AABB needs to be updated before use.
  2766. */
  2767. /**
  2768. * Total bounding radius of the Body including its shapes, relative to body.position.
  2769. */
  2770. /**
  2771. * When true the body behaves like a trigger. It does not collide
  2772. * with other bodies but collision events are still triggered.
  2773. * @default false
  2774. */
  2775. constructor(options = {}) {
  2776. super();
  2777. this.id = void 0;
  2778. this.index = void 0;
  2779. this.world = void 0;
  2780. this.preStep = void 0;
  2781. this.postStep = void 0;
  2782. this.vlambda = void 0;
  2783. this.collisionFilterGroup = void 0;
  2784. this.collisionFilterMask = void 0;
  2785. this.collisionResponse = void 0;
  2786. this.position = void 0;
  2787. this.previousPosition = void 0;
  2788. this.interpolatedPosition = void 0;
  2789. this.initPosition = void 0;
  2790. this.velocity = void 0;
  2791. this.initVelocity = void 0;
  2792. this.force = void 0;
  2793. this.mass = void 0;
  2794. this.invMass = void 0;
  2795. this.material = void 0;
  2796. this.linearDamping = void 0;
  2797. this.type = void 0;
  2798. this.allowSleep = void 0;
  2799. this.sleepState = void 0;
  2800. this.sleepSpeedLimit = void 0;
  2801. this.sleepTimeLimit = void 0;
  2802. this.timeLastSleepy = void 0;
  2803. this.wakeUpAfterNarrowphase = void 0;
  2804. this.torque = void 0;
  2805. this.quaternion = void 0;
  2806. this.initQuaternion = void 0;
  2807. this.previousQuaternion = void 0;
  2808. this.interpolatedQuaternion = void 0;
  2809. this.angularVelocity = void 0;
  2810. this.initAngularVelocity = void 0;
  2811. this.shapes = void 0;
  2812. this.shapeOffsets = void 0;
  2813. this.shapeOrientations = void 0;
  2814. this.inertia = void 0;
  2815. this.invInertia = void 0;
  2816. this.invInertiaWorld = void 0;
  2817. this.invMassSolve = void 0;
  2818. this.invInertiaSolve = void 0;
  2819. this.invInertiaWorldSolve = void 0;
  2820. this.fixedRotation = void 0;
  2821. this.angularDamping = void 0;
  2822. this.linearFactor = void 0;
  2823. this.angularFactor = void 0;
  2824. this.aabb = void 0;
  2825. this.aabbNeedsUpdate = void 0;
  2826. this.boundingRadius = void 0;
  2827. this.wlambda = void 0;
  2828. this.isTrigger = void 0;
  2829. this.id = Body.idCounter++;
  2830. this.index = -1;
  2831. this.world = null;
  2832. this.preStep = null;
  2833. this.postStep = null;
  2834. this.vlambda = new Vec3();
  2835. this.collisionFilterGroup = typeof options.collisionFilterGroup === 'number' ? options.collisionFilterGroup : 1;
  2836. this.collisionFilterMask = typeof options.collisionFilterMask === 'number' ? options.collisionFilterMask : -1;
  2837. this.collisionResponse = typeof options.collisionResponse === 'boolean' ? options.collisionResponse : true;
  2838. this.position = new Vec3();
  2839. this.previousPosition = new Vec3();
  2840. this.interpolatedPosition = new Vec3();
  2841. this.initPosition = new Vec3();
  2842. if (options.position) {
  2843. this.position.copy(options.position);
  2844. this.previousPosition.copy(options.position);
  2845. this.interpolatedPosition.copy(options.position);
  2846. this.initPosition.copy(options.position);
  2847. }
  2848. this.velocity = new Vec3();
  2849. if (options.velocity) {
  2850. this.velocity.copy(options.velocity);
  2851. }
  2852. this.initVelocity = new Vec3();
  2853. this.force = new Vec3();
  2854. const mass = typeof options.mass === 'number' ? options.mass : 0;
  2855. this.mass = mass;
  2856. this.invMass = mass > 0 ? 1.0 / mass : 0;
  2857. this.material = options.material || null;
  2858. this.linearDamping = typeof options.linearDamping === 'number' ? options.linearDamping : 0.01;
  2859. this.type = mass <= 0.0 ? Body.STATIC : Body.DYNAMIC;
  2860. if (typeof options.type === typeof Body.STATIC) {
  2861. this.type = options.type;
  2862. }
  2863. this.allowSleep = typeof options.allowSleep !== 'undefined' ? options.allowSleep : true;
  2864. this.sleepState = Body.AWAKE;
  2865. this.sleepSpeedLimit = typeof options.sleepSpeedLimit !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  2866. this.sleepTimeLimit = typeof options.sleepTimeLimit !== 'undefined' ? options.sleepTimeLimit : 1;
  2867. this.timeLastSleepy = 0;
  2868. this.wakeUpAfterNarrowphase = false;
  2869. this.torque = new Vec3();
  2870. this.quaternion = new Quaternion();
  2871. this.initQuaternion = new Quaternion();
  2872. this.previousQuaternion = new Quaternion();
  2873. this.interpolatedQuaternion = new Quaternion();
  2874. if (options.quaternion) {
  2875. this.quaternion.copy(options.quaternion);
  2876. this.initQuaternion.copy(options.quaternion);
  2877. this.previousQuaternion.copy(options.quaternion);
  2878. this.interpolatedQuaternion.copy(options.quaternion);
  2879. }
  2880. this.angularVelocity = new Vec3();
  2881. if (options.angularVelocity) {
  2882. this.angularVelocity.copy(options.angularVelocity);
  2883. }
  2884. this.initAngularVelocity = new Vec3();
  2885. this.shapes = [];
  2886. this.shapeOffsets = [];
  2887. this.shapeOrientations = [];
  2888. this.inertia = new Vec3();
  2889. this.invInertia = new Vec3();
  2890. this.invInertiaWorld = new Mat3();
  2891. this.invMassSolve = 0;
  2892. this.invInertiaSolve = new Vec3();
  2893. this.invInertiaWorldSolve = new Mat3();
  2894. this.fixedRotation = typeof options.fixedRotation !== 'undefined' ? options.fixedRotation : false;
  2895. this.angularDamping = typeof options.angularDamping !== 'undefined' ? options.angularDamping : 0.01;
  2896. this.linearFactor = new Vec3(1, 1, 1);
  2897. if (options.linearFactor) {
  2898. this.linearFactor.copy(options.linearFactor);
  2899. }
  2900. this.angularFactor = new Vec3(1, 1, 1);
  2901. if (options.angularFactor) {
  2902. this.angularFactor.copy(options.angularFactor);
  2903. }
  2904. this.aabb = new AABB();
  2905. this.aabbNeedsUpdate = true;
  2906. this.boundingRadius = 0;
  2907. this.wlambda = new Vec3();
  2908. this.isTrigger = Boolean(options.isTrigger);
  2909. if (options.shape) {
  2910. this.addShape(options.shape);
  2911. }
  2912. this.updateMassProperties();
  2913. }
  2914. /**
  2915. * Wake the body up.
  2916. */
  2917. wakeUp() {
  2918. const prevState = this.sleepState;
  2919. this.sleepState = Body.AWAKE;
  2920. this.wakeUpAfterNarrowphase = false;
  2921. if (prevState === Body.SLEEPING) {
  2922. this.dispatchEvent(Body.wakeupEvent);
  2923. }
  2924. }
  2925. /**
  2926. * Force body sleep
  2927. */
  2928. sleep() {
  2929. this.sleepState = Body.SLEEPING;
  2930. this.velocity.set(0, 0, 0);
  2931. this.angularVelocity.set(0, 0, 0);
  2932. this.wakeUpAfterNarrowphase = false;
  2933. }
  2934. /**
  2935. * Called every timestep to update internal sleep timer and change sleep state if needed.
  2936. * @param time The world time in seconds
  2937. */
  2938. sleepTick(time) {
  2939. if (this.allowSleep) {
  2940. const sleepState = this.sleepState;
  2941. const speedSquared = this.velocity.lengthSquared() + this.angularVelocity.lengthSquared();
  2942. const speedLimitSquared = this.sleepSpeedLimit ** 2;
  2943. if (sleepState === Body.AWAKE && speedSquared < speedLimitSquared) {
  2944. this.sleepState = Body.SLEEPY; // Sleepy
  2945. this.timeLastSleepy = time;
  2946. this.dispatchEvent(Body.sleepyEvent);
  2947. } else if (sleepState === Body.SLEEPY && speedSquared > speedLimitSquared) {
  2948. this.wakeUp(); // Wake up
  2949. } else if (sleepState === Body.SLEEPY && time - this.timeLastSleepy > this.sleepTimeLimit) {
  2950. this.sleep(); // Sleeping
  2951. this.dispatchEvent(Body.sleepEvent);
  2952. }
  2953. }
  2954. }
  2955. /**
  2956. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  2957. */
  2958. updateSolveMassProperties() {
  2959. if (this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC) {
  2960. this.invMassSolve = 0;
  2961. this.invInertiaSolve.setZero();
  2962. this.invInertiaWorldSolve.setZero();
  2963. } else {
  2964. this.invMassSolve = this.invMass;
  2965. this.invInertiaSolve.copy(this.invInertia);
  2966. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  2967. }
  2968. }
  2969. /**
  2970. * Convert a world point to local body frame.
  2971. */
  2972. pointToLocalFrame(worldPoint, result = new Vec3()) {
  2973. worldPoint.vsub(this.position, result);
  2974. this.quaternion.conjugate().vmult(result, result);
  2975. return result;
  2976. }
  2977. /**
  2978. * Convert a world vector to local body frame.
  2979. */
  2980. vectorToLocalFrame(worldVector, result = new Vec3()) {
  2981. this.quaternion.conjugate().vmult(worldVector, result);
  2982. return result;
  2983. }
  2984. /**
  2985. * Convert a local body point to world frame.
  2986. */
  2987. pointToWorldFrame(localPoint, result = new Vec3()) {
  2988. this.quaternion.vmult(localPoint, result);
  2989. result.vadd(this.position, result);
  2990. return result;
  2991. }
  2992. /**
  2993. * Convert a local body point to world frame.
  2994. */
  2995. vectorToWorldFrame(localVector, result = new Vec3()) {
  2996. this.quaternion.vmult(localVector, result);
  2997. return result;
  2998. }
  2999. /**
  3000. * Add a shape to the body with a local offset and orientation.
  3001. * @return The body object, for chainability.
  3002. */
  3003. addShape(shape, _offset, _orientation) {
  3004. const offset = new Vec3();
  3005. const orientation = new Quaternion();
  3006. if (_offset) {
  3007. offset.copy(_offset);
  3008. }
  3009. if (_orientation) {
  3010. orientation.copy(_orientation);
  3011. }
  3012. this.shapes.push(shape);
  3013. this.shapeOffsets.push(offset);
  3014. this.shapeOrientations.push(orientation);
  3015. this.updateMassProperties();
  3016. this.updateBoundingRadius();
  3017. this.aabbNeedsUpdate = true;
  3018. shape.body = this;
  3019. return this;
  3020. }
  3021. /**
  3022. * Remove a shape from the body.
  3023. * @return The body object, for chainability.
  3024. */
  3025. removeShape(shape) {
  3026. const index = this.shapes.indexOf(shape);
  3027. if (index === -1) {
  3028. console.warn('Shape does not belong to the body');
  3029. return this;
  3030. }
  3031. this.shapes.splice(index, 1);
  3032. this.shapeOffsets.splice(index, 1);
  3033. this.shapeOrientations.splice(index, 1);
  3034. this.updateMassProperties();
  3035. this.updateBoundingRadius();
  3036. this.aabbNeedsUpdate = true;
  3037. shape.body = null;
  3038. return this;
  3039. }
  3040. /**
  3041. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  3042. */
  3043. updateBoundingRadius() {
  3044. const shapes = this.shapes;
  3045. const shapeOffsets = this.shapeOffsets;
  3046. const N = shapes.length;
  3047. let radius = 0;
  3048. for (let i = 0; i !== N; i++) {
  3049. const shape = shapes[i];
  3050. shape.updateBoundingSphereRadius();
  3051. const offset = shapeOffsets[i].length();
  3052. const r = shape.boundingSphereRadius;
  3053. if (offset + r > radius) {
  3054. radius = offset + r;
  3055. }
  3056. }
  3057. this.boundingRadius = radius;
  3058. }
  3059. /**
  3060. * Updates the .aabb
  3061. */
  3062. updateAABB() {
  3063. const shapes = this.shapes;
  3064. const shapeOffsets = this.shapeOffsets;
  3065. const shapeOrientations = this.shapeOrientations;
  3066. const N = shapes.length;
  3067. const offset = tmpVec;
  3068. const orientation = tmpQuat;
  3069. const bodyQuat = this.quaternion;
  3070. const aabb = this.aabb;
  3071. const shapeAABB = updateAABB_shapeAABB;
  3072. for (let i = 0; i !== N; i++) {
  3073. const shape = shapes[i]; // Get shape world position
  3074. bodyQuat.vmult(shapeOffsets[i], offset);
  3075. offset.vadd(this.position, offset); // Get shape world quaternion
  3076. bodyQuat.mult(shapeOrientations[i], orientation); // Get shape AABB
  3077. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  3078. if (i === 0) {
  3079. aabb.copy(shapeAABB);
  3080. } else {
  3081. aabb.extend(shapeAABB);
  3082. }
  3083. }
  3084. this.aabbNeedsUpdate = false;
  3085. }
  3086. /**
  3087. * Update `.inertiaWorld` and `.invInertiaWorld`
  3088. */
  3089. updateInertiaWorld(force) {
  3090. const I = this.invInertia;
  3091. if (I.x === I.y && I.y === I.z && !force) ; else {
  3092. const m1 = uiw_m1;
  3093. const m2 = uiw_m2;
  3094. m1.setRotationFromQuaternion(this.quaternion);
  3095. m1.transpose(m2);
  3096. m1.scale(I, m1);
  3097. m1.mmult(m2, this.invInertiaWorld);
  3098. }
  3099. }
  3100. /**
  3101. * Apply force to a point of the body. This could for example be a point on the Body surface.
  3102. * Applying force this way will add to Body.force and Body.torque.
  3103. * @param force The amount of force to add.
  3104. * @param relativePoint A point relative to the center of mass to apply the force on.
  3105. */
  3106. applyForce(force, relativePoint = new Vec3()) {
  3107. // Needed?
  3108. if (this.type !== Body.DYNAMIC) {
  3109. return;
  3110. }
  3111. if (this.sleepState === Body.SLEEPING) {
  3112. this.wakeUp();
  3113. } // Compute produced rotational force
  3114. const rotForce = Body_applyForce_rotForce;
  3115. relativePoint.cross(force, rotForce); // Add linear force
  3116. this.force.vadd(force, this.force); // Add rotational force
  3117. this.torque.vadd(rotForce, this.torque);
  3118. }
  3119. /**
  3120. * Apply force to a local point in the body.
  3121. * @param force The force vector to apply, defined locally in the body frame.
  3122. * @param localPoint A local point in the body to apply the force on.
  3123. */
  3124. applyLocalForce(localForce, localPoint = new Vec3()) {
  3125. if (this.type !== Body.DYNAMIC) {
  3126. return;
  3127. }
  3128. const worldForce = Body_applyLocalForce_worldForce;
  3129. const relativePointWorld = Body_applyLocalForce_relativePointWorld; // Transform the force vector to world space
  3130. this.vectorToWorldFrame(localForce, worldForce);
  3131. this.vectorToWorldFrame(localPoint, relativePointWorld);
  3132. this.applyForce(worldForce, relativePointWorld);
  3133. }
  3134. /**
  3135. * Apply torque to the body.
  3136. * @param torque The amount of torque to add.
  3137. */
  3138. applyTorque(torque) {
  3139. if (this.type !== Body.DYNAMIC) {
  3140. return;
  3141. }
  3142. if (this.sleepState === Body.SLEEPING) {
  3143. this.wakeUp();
  3144. } // Add rotational force
  3145. this.torque.vadd(torque, this.torque);
  3146. }
  3147. /**
  3148. * Apply impulse to a point of the body. This could for example be a point on the Body surface.
  3149. * An impulse is a force added to a body during a short period of time (impulse = force * time).
  3150. * Impulses will be added to Body.velocity and Body.angularVelocity.
  3151. * @param impulse The amount of impulse to add.
  3152. * @param relativePoint A point relative to the center of mass to apply the force on.
  3153. */
  3154. applyImpulse(impulse, relativePoint = new Vec3()) {
  3155. if (this.type !== Body.DYNAMIC) {
  3156. return;
  3157. }
  3158. if (this.sleepState === Body.SLEEPING) {
  3159. this.wakeUp();
  3160. } // Compute point position relative to the body center
  3161. const r = relativePoint; // Compute produced central impulse velocity
  3162. const velo = Body_applyImpulse_velo;
  3163. velo.copy(impulse);
  3164. velo.scale(this.invMass, velo); // Add linear impulse
  3165. this.velocity.vadd(velo, this.velocity); // Compute produced rotational impulse velocity
  3166. const rotVelo = Body_applyImpulse_rotVelo;
  3167. r.cross(impulse, rotVelo);
  3168. /*
  3169. rotVelo.x *= this.invInertia.x;
  3170. rotVelo.y *= this.invInertia.y;
  3171. rotVelo.z *= this.invInertia.z;
  3172. */
  3173. this.invInertiaWorld.vmult(rotVelo, rotVelo); // Add rotational Impulse
  3174. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  3175. }
  3176. /**
  3177. * Apply locally-defined impulse to a local point in the body.
  3178. * @param force The force vector to apply, defined locally in the body frame.
  3179. * @param localPoint A local point in the body to apply the force on.
  3180. */
  3181. applyLocalImpulse(localImpulse, localPoint = new Vec3()) {
  3182. if (this.type !== Body.DYNAMIC) {
  3183. return;
  3184. }
  3185. const worldImpulse = Body_applyLocalImpulse_worldImpulse;
  3186. const relativePointWorld = Body_applyLocalImpulse_relativePoint; // Transform the force vector to world space
  3187. this.vectorToWorldFrame(localImpulse, worldImpulse);
  3188. this.vectorToWorldFrame(localPoint, relativePointWorld);
  3189. this.applyImpulse(worldImpulse, relativePointWorld);
  3190. }
  3191. /**
  3192. * Should be called whenever you change the body shape or mass.
  3193. */
  3194. updateMassProperties() {
  3195. const halfExtents = Body_updateMassProperties_halfExtents;
  3196. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  3197. const I = this.inertia;
  3198. const fixed = this.fixedRotation; // Approximate with AABB box
  3199. this.updateAABB();
  3200. halfExtents.set((this.aabb.upperBound.x - this.aabb.lowerBound.x) / 2, (this.aabb.upperBound.y - this.aabb.lowerBound.y) / 2, (this.aabb.upperBound.z - this.aabb.lowerBound.z) / 2);
  3201. Box.calculateInertia(halfExtents, this.mass, I);
  3202. this.invInertia.set(I.x > 0 && !fixed ? 1.0 / I.x : 0, I.y > 0 && !fixed ? 1.0 / I.y : 0, I.z > 0 && !fixed ? 1.0 / I.z : 0);
  3203. this.updateInertiaWorld(true);
  3204. }
  3205. /**
  3206. * Get world velocity of a point in the body.
  3207. * @param worldPoint
  3208. * @param result
  3209. * @return The result vector.
  3210. */
  3211. getVelocityAtWorldPoint(worldPoint, result) {
  3212. const r = new Vec3();
  3213. worldPoint.vsub(this.position, r);
  3214. this.angularVelocity.cross(r, result);
  3215. this.velocity.vadd(result, result);
  3216. return result;
  3217. }
  3218. /**
  3219. * Move the body forward in time.
  3220. * @param dt Time step
  3221. * @param quatNormalize Set to true to normalize the body quaternion
  3222. * @param quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
  3223. */
  3224. integrate(dt, quatNormalize, quatNormalizeFast) {
  3225. // Save previous position
  3226. this.previousPosition.copy(this.position);
  3227. this.previousQuaternion.copy(this.quaternion);
  3228. if (!(this.type === Body.DYNAMIC || this.type === Body.KINEMATIC) || this.sleepState === Body.SLEEPING) {
  3229. // Only for dynamic
  3230. return;
  3231. }
  3232. const velo = this.velocity;
  3233. const angularVelo = this.angularVelocity;
  3234. const pos = this.position;
  3235. const force = this.force;
  3236. const torque = this.torque;
  3237. const quat = this.quaternion;
  3238. const invMass = this.invMass;
  3239. const invInertia = this.invInertiaWorld;
  3240. const linearFactor = this.linearFactor;
  3241. const iMdt = invMass * dt;
  3242. velo.x += force.x * iMdt * linearFactor.x;
  3243. velo.y += force.y * iMdt * linearFactor.y;
  3244. velo.z += force.z * iMdt * linearFactor.z;
  3245. const e = invInertia.elements;
  3246. const angularFactor = this.angularFactor;
  3247. const tx = torque.x * angularFactor.x;
  3248. const ty = torque.y * angularFactor.y;
  3249. const tz = torque.z * angularFactor.z;
  3250. angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);
  3251. angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);
  3252. angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz); // Use new velocity - leap frog
  3253. pos.x += velo.x * dt;
  3254. pos.y += velo.y * dt;
  3255. pos.z += velo.z * dt;
  3256. quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);
  3257. if (quatNormalize) {
  3258. if (quatNormalizeFast) {
  3259. quat.normalizeFast();
  3260. } else {
  3261. quat.normalize();
  3262. }
  3263. }
  3264. this.aabbNeedsUpdate = true; // Update world inertia
  3265. this.updateInertiaWorld();
  3266. }
  3267. }
  3268. Body.idCounter = 0;
  3269. Body.COLLIDE_EVENT_NAME = 'collide';
  3270. Body.DYNAMIC = BODY_TYPES.DYNAMIC;
  3271. Body.STATIC = BODY_TYPES.STATIC;
  3272. Body.KINEMATIC = BODY_TYPES.KINEMATIC;
  3273. Body.AWAKE = BODY_SLEEP_STATES.AWAKE;
  3274. Body.SLEEPY = BODY_SLEEP_STATES.SLEEPY;
  3275. Body.SLEEPING = BODY_SLEEP_STATES.SLEEPING;
  3276. Body.wakeupEvent = {
  3277. type: 'wakeup'
  3278. };
  3279. Body.sleepyEvent = {
  3280. type: 'sleepy'
  3281. };
  3282. Body.sleepEvent = {
  3283. type: 'sleep'
  3284. };
  3285. const tmpVec = new Vec3();
  3286. const tmpQuat = new Quaternion();
  3287. const updateAABB_shapeAABB = new AABB();
  3288. const uiw_m1 = new Mat3();
  3289. const uiw_m2 = new Mat3();
  3290. const Body_applyForce_rotForce = new Vec3();
  3291. const Body_applyLocalForce_worldForce = new Vec3();
  3292. const Body_applyLocalForce_relativePointWorld = new Vec3();
  3293. const Body_applyImpulse_velo = new Vec3();
  3294. const Body_applyImpulse_rotVelo = new Vec3();
  3295. const Body_applyLocalImpulse_worldImpulse = new Vec3();
  3296. const Body_applyLocalImpulse_relativePoint = new Vec3();
  3297. const Body_updateMassProperties_halfExtents = new Vec3();
  3298. /**
  3299. * Base class for broadphase implementations
  3300. * @author schteppe
  3301. */
  3302. class Broadphase {
  3303. /**
  3304. * The world to search for collisions in.
  3305. */
  3306. /**
  3307. * If set to true, the broadphase uses bounding boxes for intersection tests, else it uses bounding spheres.
  3308. */
  3309. /**
  3310. * Set to true if the objects in the world moved.
  3311. */
  3312. constructor() {
  3313. this.world = void 0;
  3314. this.useBoundingBoxes = void 0;
  3315. this.dirty = void 0;
  3316. this.world = null;
  3317. this.useBoundingBoxes = false;
  3318. this.dirty = true;
  3319. }
  3320. /**
  3321. * Get the collision pairs from the world
  3322. * @param world The world to search in
  3323. * @param p1 Empty array to be filled with body objects
  3324. * @param p2 Empty array to be filled with body objects
  3325. */
  3326. collisionPairs(world, p1, p2) {
  3327. throw new Error('collisionPairs not implemented for this BroadPhase class!');
  3328. }
  3329. /**
  3330. * Check if a body pair needs to be intersection tested at all.
  3331. */
  3332. needBroadphaseCollision(bodyA, bodyB) {
  3333. // Check collision filter masks
  3334. if ((bodyA.collisionFilterGroup & bodyB.collisionFilterMask) === 0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask) === 0) {
  3335. return false;
  3336. } // Check types
  3337. if (((bodyA.type & Body.STATIC) !== 0 || bodyA.sleepState === Body.SLEEPING) && ((bodyB.type & Body.STATIC) !== 0 || bodyB.sleepState === Body.SLEEPING)) {
  3338. // Both bodies are static or sleeping. Skip.
  3339. return false;
  3340. }
  3341. return true;
  3342. }
  3343. /**
  3344. * Check if the bounding volumes of two bodies intersect.
  3345. */
  3346. intersectionTest(bodyA, bodyB, pairs1, pairs2) {
  3347. if (this.useBoundingBoxes) {
  3348. this.doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2);
  3349. } else {
  3350. this.doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2);
  3351. }
  3352. }
  3353. /**
  3354. * Check if the bounding spheres of two bodies are intersecting.
  3355. * @param pairs1 bodyA is appended to this array if intersection
  3356. * @param pairs2 bodyB is appended to this array if intersection
  3357. */
  3358. doBoundingSphereBroadphase(bodyA, bodyB, pairs1, pairs2) {
  3359. const r = Broadphase_collisionPairs_r;
  3360. bodyB.position.vsub(bodyA.position, r);
  3361. const boundingRadiusSum2 = (bodyA.boundingRadius + bodyB.boundingRadius) ** 2;
  3362. const norm2 = r.lengthSquared();
  3363. if (norm2 < boundingRadiusSum2) {
  3364. pairs1.push(bodyA);
  3365. pairs2.push(bodyB);
  3366. }
  3367. }
  3368. /**
  3369. * Check if the bounding boxes of two bodies are intersecting.
  3370. */
  3371. doBoundingBoxBroadphase(bodyA, bodyB, pairs1, pairs2) {
  3372. if (bodyA.aabbNeedsUpdate) {
  3373. bodyA.updateAABB();
  3374. }
  3375. if (bodyB.aabbNeedsUpdate) {
  3376. bodyB.updateAABB();
  3377. } // Check AABB / AABB
  3378. if (bodyA.aabb.overlaps(bodyB.aabb)) {
  3379. pairs1.push(bodyA);
  3380. pairs2.push(bodyB);
  3381. }
  3382. }
  3383. /**
  3384. * Removes duplicate pairs from the pair arrays.
  3385. */
  3386. makePairsUnique(pairs1, pairs2) {
  3387. const t = Broadphase_makePairsUnique_temp;
  3388. const p1 = Broadphase_makePairsUnique_p1;
  3389. const p2 = Broadphase_makePairsUnique_p2;
  3390. const N = pairs1.length;
  3391. for (let i = 0; i !== N; i++) {
  3392. p1[i] = pairs1[i];
  3393. p2[i] = pairs2[i];
  3394. }
  3395. pairs1.length = 0;
  3396. pairs2.length = 0;
  3397. for (let i = 0; i !== N; i++) {
  3398. const id1 = p1[i].id;
  3399. const id2 = p2[i].id;
  3400. const key = id1 < id2 ? id1 + "," + id2 : id2 + "," + id1;
  3401. t[key] = i;
  3402. t.keys.push(key);
  3403. }
  3404. for (let i = 0; i !== t.keys.length; i++) {
  3405. const key = t.keys.pop();
  3406. const pairIndex = t[key];
  3407. pairs1.push(p1[pairIndex]);
  3408. pairs2.push(p2[pairIndex]);
  3409. delete t[key];
  3410. }
  3411. }
  3412. /**
  3413. * To be implemented by subcasses
  3414. */
  3415. setWorld(world) {}
  3416. /**
  3417. * Check if the bounding spheres of two bodies overlap.
  3418. */
  3419. static boundingSphereCheck(bodyA, bodyB) {
  3420. const dist = new Vec3(); // bsc_dist;
  3421. bodyA.position.vsub(bodyB.position, dist);
  3422. const sa = bodyA.shapes[0];
  3423. const sb = bodyB.shapes[0];
  3424. return Math.pow(sa.boundingSphereRadius + sb.boundingSphereRadius, 2) > dist.lengthSquared();
  3425. }
  3426. /**
  3427. * Returns all the bodies within the AABB.
  3428. */
  3429. aabbQuery(world, aabb, result) {
  3430. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  3431. return [];
  3432. }
  3433. } // Temp objects
  3434. const Broadphase_collisionPairs_r = new Vec3();
  3435. const Broadphase_makePairsUnique_temp = {
  3436. keys: []
  3437. };
  3438. const Broadphase_makePairsUnique_p1 = [];
  3439. const Broadphase_makePairsUnique_p2 = [];
  3440. /**
  3441. * Axis aligned uniform grid broadphase.
  3442. * @todo Needs support for more than just planes and spheres.
  3443. */
  3444. class GridBroadphase extends Broadphase {
  3445. /**
  3446. * Number of boxes along x
  3447. */
  3448. /**
  3449. * Number of boxes along y
  3450. */
  3451. /**
  3452. * Number of boxes along z
  3453. */
  3454. /**
  3455. * aabbMin
  3456. */
  3457. /**
  3458. * aabbMax
  3459. */
  3460. /**
  3461. * bins
  3462. */
  3463. /**
  3464. * binLengths
  3465. */
  3466. /**
  3467. * @param nx Number of boxes along x.
  3468. * @param ny Number of boxes along y.
  3469. * @param nz Number of boxes along z.
  3470. */
  3471. constructor(aabbMin = new Vec3(100, 100, 100), aabbMax = new Vec3(-100, -100, -100), nx = 10, ny = 10, nz = 10) {
  3472. super();
  3473. this.nx = void 0;
  3474. this.ny = void 0;
  3475. this.nz = void 0;
  3476. this.aabbMin = void 0;
  3477. this.aabbMax = void 0;
  3478. this.bins = void 0;
  3479. this.binLengths = void 0;
  3480. this.nx = nx;
  3481. this.ny = ny;
  3482. this.nz = nz;
  3483. this.aabbMin = aabbMin;
  3484. this.aabbMax = aabbMax;
  3485. const nbins = this.nx * this.ny * this.nz;
  3486. if (nbins <= 0) {
  3487. throw "GridBroadphase: Each dimension's n must be >0";
  3488. }
  3489. this.bins = [];
  3490. this.binLengths = []; // Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  3491. this.bins.length = nbins;
  3492. this.binLengths.length = nbins;
  3493. for (let i = 0; i < nbins; i++) {
  3494. this.bins[i] = [];
  3495. this.binLengths[i] = 0;
  3496. }
  3497. }
  3498. /**
  3499. * Get all the collision pairs in the physics world
  3500. */
  3501. collisionPairs(world, pairs1, pairs2) {
  3502. const N = world.numObjects();
  3503. const bodies = world.bodies;
  3504. const max = this.aabbMax;
  3505. const min = this.aabbMin;
  3506. const nx = this.nx;
  3507. const ny = this.ny;
  3508. const nz = this.nz;
  3509. const xstep = ny * nz;
  3510. const ystep = nz;
  3511. const zstep = 1;
  3512. const xmax = max.x;
  3513. const ymax = max.y;
  3514. const zmax = max.z;
  3515. const xmin = min.x;
  3516. const ymin = min.y;
  3517. const zmin = min.z;
  3518. const xmult = nx / (xmax - xmin);
  3519. const ymult = ny / (ymax - ymin);
  3520. const zmult = nz / (zmax - zmin);
  3521. const binsizeX = (xmax - xmin) / nx;
  3522. const binsizeY = (ymax - ymin) / ny;
  3523. const binsizeZ = (zmax - zmin) / nz;
  3524. const binRadius = Math.sqrt(binsizeX * binsizeX + binsizeY * binsizeY + binsizeZ * binsizeZ) * 0.5;
  3525. const types = Shape.types;
  3526. const SPHERE = types.SPHERE;
  3527. const PLANE = types.PLANE;
  3528. types.BOX;
  3529. types.COMPOUND;
  3530. types.CONVEXPOLYHEDRON;
  3531. const bins = this.bins;
  3532. const binLengths = this.binLengths;
  3533. const Nbins = this.bins.length; // Reset bins
  3534. for (let i = 0; i !== Nbins; i++) {
  3535. binLengths[i] = 0;
  3536. }
  3537. const ceil = Math.ceil;
  3538. function addBoxToBins(x0, y0, z0, x1, y1, z1, bi) {
  3539. let xoff0 = (x0 - xmin) * xmult | 0;
  3540. let yoff0 = (y0 - ymin) * ymult | 0;
  3541. let zoff0 = (z0 - zmin) * zmult | 0;
  3542. let xoff1 = ceil((x1 - xmin) * xmult);
  3543. let yoff1 = ceil((y1 - ymin) * ymult);
  3544. let zoff1 = ceil((z1 - zmin) * zmult);
  3545. if (xoff0 < 0) {
  3546. xoff0 = 0;
  3547. } else if (xoff0 >= nx) {
  3548. xoff0 = nx - 1;
  3549. }
  3550. if (yoff0 < 0) {
  3551. yoff0 = 0;
  3552. } else if (yoff0 >= ny) {
  3553. yoff0 = ny - 1;
  3554. }
  3555. if (zoff0 < 0) {
  3556. zoff0 = 0;
  3557. } else if (zoff0 >= nz) {
  3558. zoff0 = nz - 1;
  3559. }
  3560. if (xoff1 < 0) {
  3561. xoff1 = 0;
  3562. } else if (xoff1 >= nx) {
  3563. xoff1 = nx - 1;
  3564. }
  3565. if (yoff1 < 0) {
  3566. yoff1 = 0;
  3567. } else if (yoff1 >= ny) {
  3568. yoff1 = ny - 1;
  3569. }
  3570. if (zoff1 < 0) {
  3571. zoff1 = 0;
  3572. } else if (zoff1 >= nz) {
  3573. zoff1 = nz - 1;
  3574. }
  3575. xoff0 *= xstep;
  3576. yoff0 *= ystep;
  3577. zoff0 *= zstep;
  3578. xoff1 *= xstep;
  3579. yoff1 *= ystep;
  3580. zoff1 *= zstep;
  3581. for (let xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  3582. for (let yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  3583. for (let zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  3584. const idx = xoff + yoff + zoff;
  3585. bins[idx][binLengths[idx]++] = bi;
  3586. }
  3587. }
  3588. }
  3589. } // Put all bodies into the bins
  3590. for (let i = 0; i !== N; i++) {
  3591. const bi = bodies[i];
  3592. const si = bi.shapes[0];
  3593. switch (si.type) {
  3594. case SPHERE:
  3595. {
  3596. const shape = si; // Put in bin
  3597. // check if overlap with other bins
  3598. const x = bi.position.x;
  3599. const y = bi.position.y;
  3600. const z = bi.position.z;
  3601. const r = shape.radius;
  3602. addBoxToBins(x - r, y - r, z - r, x + r, y + r, z + r, bi);
  3603. break;
  3604. }
  3605. case PLANE:
  3606. {
  3607. const shape = si;
  3608. if (shape.worldNormalNeedsUpdate) {
  3609. shape.computeWorldNormal(bi.quaternion);
  3610. }
  3611. const planeNormal = shape.worldNormal; //Relative position from origin of plane object to the first bin
  3612. //Incremented as we iterate through the bins
  3613. const xreset = xmin + binsizeX * 0.5 - bi.position.x;
  3614. const yreset = ymin + binsizeY * 0.5 - bi.position.y;
  3615. const zreset = zmin + binsizeZ * 0.5 - bi.position.z;
  3616. const d = GridBroadphase_collisionPairs_d;
  3617. d.set(xreset, yreset, zreset);
  3618. for (let xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  3619. for (let yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  3620. for (let zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  3621. if (d.dot(planeNormal) < binRadius) {
  3622. const idx = xoff + yoff + zoff;
  3623. bins[idx][binLengths[idx]++] = bi;
  3624. }
  3625. }
  3626. }
  3627. }
  3628. break;
  3629. }
  3630. default:
  3631. {
  3632. if (bi.aabbNeedsUpdate) {
  3633. bi.updateAABB();
  3634. }
  3635. addBoxToBins(bi.aabb.lowerBound.x, bi.aabb.lowerBound.y, bi.aabb.lowerBound.z, bi.aabb.upperBound.x, bi.aabb.upperBound.y, bi.aabb.upperBound.z, bi);
  3636. break;
  3637. }
  3638. }
  3639. } // Check each bin
  3640. for (let i = 0; i !== Nbins; i++) {
  3641. const binLength = binLengths[i]; //Skip bins with no potential collisions
  3642. if (binLength > 1) {
  3643. const bin = bins[i]; // Do N^2 broadphase inside
  3644. for (let xi = 0; xi !== binLength; xi++) {
  3645. const bi = bin[xi];
  3646. for (let yi = 0; yi !== xi; yi++) {
  3647. const bj = bin[yi];
  3648. if (this.needBroadphaseCollision(bi, bj)) {
  3649. this.intersectionTest(bi, bj, pairs1, pairs2);
  3650. }
  3651. }
  3652. }
  3653. }
  3654. } // for (let zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  3655. // console.log("layer "+zi);
  3656. // for (let yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  3657. // const row = '';
  3658. // for (let xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  3659. // const idx = xoff + yoff + zoff;
  3660. // row += ' ' + binLengths[idx];
  3661. // }
  3662. // console.log(row);
  3663. // }
  3664. // }
  3665. this.makePairsUnique(pairs1, pairs2);
  3666. }
  3667. }
  3668. const GridBroadphase_collisionPairs_d = new Vec3();
  3669. /**
  3670. * Naive broadphase implementation, used in lack of better ones.
  3671. *
  3672. * The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 _(which is bad)_
  3673. */
  3674. class NaiveBroadphase extends Broadphase {
  3675. /**
  3676. * @todo Remove useless constructor
  3677. */
  3678. constructor() {
  3679. super();
  3680. }
  3681. /**
  3682. * Get all the collision pairs in the physics world
  3683. */
  3684. collisionPairs(world, pairs1, pairs2) {
  3685. const bodies = world.bodies;
  3686. const n = bodies.length;
  3687. let bi;
  3688. let bj; // Naive N^2 ftw!
  3689. for (let i = 0; i !== n; i++) {
  3690. for (let j = 0; j !== i; j++) {
  3691. bi = bodies[i];
  3692. bj = bodies[j];
  3693. if (!this.needBroadphaseCollision(bi, bj)) {
  3694. continue;
  3695. }
  3696. this.intersectionTest(bi, bj, pairs1, pairs2);
  3697. }
  3698. }
  3699. }
  3700. /**
  3701. * Returns all the bodies within an AABB.
  3702. * @param result An array to store resulting bodies in.
  3703. */
  3704. aabbQuery(world, aabb, result = []) {
  3705. for (let i = 0; i < world.bodies.length; i++) {
  3706. const b = world.bodies[i];
  3707. if (b.aabbNeedsUpdate) {
  3708. b.updateAABB();
  3709. } // Ugly hack until Body gets aabb
  3710. if (b.aabb.overlaps(aabb)) {
  3711. result.push(b);
  3712. }
  3713. }
  3714. return result;
  3715. }
  3716. }
  3717. /**
  3718. * Storage for Ray casting data
  3719. */
  3720. class RaycastResult {
  3721. /**
  3722. * rayFromWorld
  3723. */
  3724. /**
  3725. * rayToWorld
  3726. */
  3727. /**
  3728. * hitNormalWorld
  3729. */
  3730. /**
  3731. * hitPointWorld
  3732. */
  3733. /**
  3734. * hasHit
  3735. */
  3736. /**
  3737. * shape
  3738. */
  3739. /**
  3740. * body
  3741. */
  3742. /**
  3743. * The index of the hit triangle, if the hit shape was a trimesh
  3744. */
  3745. /**
  3746. * Distance to the hit. Will be set to -1 if there was no hit
  3747. */
  3748. /**
  3749. * If the ray should stop traversing the bodies
  3750. */
  3751. constructor() {
  3752. this.rayFromWorld = void 0;
  3753. this.rayToWorld = void 0;
  3754. this.hitNormalWorld = void 0;
  3755. this.hitPointWorld = void 0;
  3756. this.hasHit = void 0;
  3757. this.shape = void 0;
  3758. this.body = void 0;
  3759. this.hitFaceIndex = void 0;
  3760. this.distance = void 0;
  3761. this.shouldStop = void 0;
  3762. this.rayFromWorld = new Vec3();
  3763. this.rayToWorld = new Vec3();
  3764. this.hitNormalWorld = new Vec3();
  3765. this.hitPointWorld = new Vec3();
  3766. this.hasHit = false;
  3767. this.shape = null;
  3768. this.body = null;
  3769. this.hitFaceIndex = -1;
  3770. this.distance = -1;
  3771. this.shouldStop = false;
  3772. }
  3773. /**
  3774. * Reset all result data.
  3775. */
  3776. reset() {
  3777. this.rayFromWorld.setZero();
  3778. this.rayToWorld.setZero();
  3779. this.hitNormalWorld.setZero();
  3780. this.hitPointWorld.setZero();
  3781. this.hasHit = false;
  3782. this.shape = null;
  3783. this.body = null;
  3784. this.hitFaceIndex = -1;
  3785. this.distance = -1;
  3786. this.shouldStop = false;
  3787. }
  3788. /**
  3789. * abort
  3790. */
  3791. abort() {
  3792. this.shouldStop = true;
  3793. }
  3794. /**
  3795. * Set result data.
  3796. */
  3797. set(rayFromWorld, rayToWorld, hitNormalWorld, hitPointWorld, shape, body, distance) {
  3798. this.rayFromWorld.copy(rayFromWorld);
  3799. this.rayToWorld.copy(rayToWorld);
  3800. this.hitNormalWorld.copy(hitNormalWorld);
  3801. this.hitPointWorld.copy(hitPointWorld);
  3802. this.shape = shape;
  3803. this.body = body;
  3804. this.distance = distance;
  3805. }
  3806. }
  3807. let _Shape$types$SPHERE, _Shape$types$PLANE, _Shape$types$BOX, _Shape$types$CYLINDER, _Shape$types$CONVEXPO, _Shape$types$HEIGHTFI, _Shape$types$TRIMESH;
  3808. /**
  3809. * RAY_MODES
  3810. */
  3811. const RAY_MODES = {
  3812. /** CLOSEST */
  3813. CLOSEST: 1,
  3814. /** ANY */
  3815. ANY: 2,
  3816. /** ALL */
  3817. ALL: 4
  3818. };
  3819. /**
  3820. * RayMode
  3821. */
  3822. _Shape$types$SPHERE = Shape.types.SPHERE;
  3823. _Shape$types$PLANE = Shape.types.PLANE;
  3824. _Shape$types$BOX = Shape.types.BOX;
  3825. _Shape$types$CYLINDER = Shape.types.CYLINDER;
  3826. _Shape$types$CONVEXPO = Shape.types.CONVEXPOLYHEDRON;
  3827. _Shape$types$HEIGHTFI = Shape.types.HEIGHTFIELD;
  3828. _Shape$types$TRIMESH = Shape.types.TRIMESH;
  3829. /**
  3830. * A line in 3D space that intersects bodies and return points.
  3831. */
  3832. class Ray {
  3833. /**
  3834. * from
  3835. */
  3836. /**
  3837. * to
  3838. */
  3839. /**
  3840. * direction
  3841. */
  3842. /**
  3843. * The precision of the ray. Used when checking parallelity etc.
  3844. * @default 0.0001
  3845. */
  3846. /**
  3847. * Set to `false` if you don't want the Ray to take `collisionResponse` flags into account on bodies and shapes.
  3848. * @default true
  3849. */
  3850. /**
  3851. * If set to `true`, the ray skips any hits with normal.dot(rayDirection) < 0.
  3852. * @default false
  3853. */
  3854. /**
  3855. * collisionFilterMask
  3856. * @default -1
  3857. */
  3858. /**
  3859. * collisionFilterGroup
  3860. * @default -1
  3861. */
  3862. /**
  3863. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  3864. * @default RAY.ANY
  3865. */
  3866. /**
  3867. * Current result object.
  3868. */
  3869. /**
  3870. * Will be set to `true` during intersectWorld() if the ray hit anything.
  3871. */
  3872. /**
  3873. * User-provided result callback. Will be used if mode is Ray.ALL.
  3874. */
  3875. /**
  3876. * CLOSEST
  3877. */
  3878. /**
  3879. * ANY
  3880. */
  3881. /**
  3882. * ALL
  3883. */
  3884. get [_Shape$types$SPHERE]() {
  3885. return this._intersectSphere;
  3886. }
  3887. get [_Shape$types$PLANE]() {
  3888. return this._intersectPlane;
  3889. }
  3890. get [_Shape$types$BOX]() {
  3891. return this._intersectBox;
  3892. }
  3893. get [_Shape$types$CYLINDER]() {
  3894. return this._intersectConvex;
  3895. }
  3896. get [_Shape$types$CONVEXPO]() {
  3897. return this._intersectConvex;
  3898. }
  3899. get [_Shape$types$HEIGHTFI]() {
  3900. return this._intersectHeightfield;
  3901. }
  3902. get [_Shape$types$TRIMESH]() {
  3903. return this._intersectTrimesh;
  3904. }
  3905. constructor(from = new Vec3(), to = new Vec3()) {
  3906. this.from = void 0;
  3907. this.to = void 0;
  3908. this.direction = void 0;
  3909. this.precision = void 0;
  3910. this.checkCollisionResponse = void 0;
  3911. this.skipBackfaces = void 0;
  3912. this.collisionFilterMask = void 0;
  3913. this.collisionFilterGroup = void 0;
  3914. this.mode = void 0;
  3915. this.result = void 0;
  3916. this.hasHit = void 0;
  3917. this.callback = void 0;
  3918. this.from = from.clone();
  3919. this.to = to.clone();
  3920. this.direction = new Vec3();
  3921. this.precision = 0.0001;
  3922. this.checkCollisionResponse = true;
  3923. this.skipBackfaces = false;
  3924. this.collisionFilterMask = -1;
  3925. this.collisionFilterGroup = -1;
  3926. this.mode = Ray.ANY;
  3927. this.result = new RaycastResult();
  3928. this.hasHit = false;
  3929. this.callback = result => {};
  3930. }
  3931. /**
  3932. * Do itersection against all bodies in the given World.
  3933. * @return True if the ray hit anything, otherwise false.
  3934. */
  3935. intersectWorld(world, options) {
  3936. this.mode = options.mode || Ray.ANY;
  3937. this.result = options.result || new RaycastResult();
  3938. this.skipBackfaces = !!options.skipBackfaces;
  3939. this.collisionFilterMask = typeof options.collisionFilterMask !== 'undefined' ? options.collisionFilterMask : -1;
  3940. this.collisionFilterGroup = typeof options.collisionFilterGroup !== 'undefined' ? options.collisionFilterGroup : -1;
  3941. this.checkCollisionResponse = typeof options.checkCollisionResponse !== 'undefined' ? options.checkCollisionResponse : true;
  3942. if (options.from) {
  3943. this.from.copy(options.from);
  3944. }
  3945. if (options.to) {
  3946. this.to.copy(options.to);
  3947. }
  3948. this.callback = options.callback || (() => {});
  3949. this.hasHit = false;
  3950. this.result.reset();
  3951. this.updateDirection();
  3952. this.getAABB(tmpAABB$1);
  3953. tmpArray.length = 0;
  3954. world.broadphase.aabbQuery(world, tmpAABB$1, tmpArray);
  3955. this.intersectBodies(tmpArray);
  3956. return this.hasHit;
  3957. }
  3958. /**
  3959. * Shoot a ray at a body, get back information about the hit.
  3960. * @deprecated @param result set the result property of the Ray instead.
  3961. */
  3962. intersectBody(body, result) {
  3963. if (result) {
  3964. this.result = result;
  3965. this.updateDirection();
  3966. }
  3967. const checkCollisionResponse = this.checkCollisionResponse;
  3968. if (checkCollisionResponse && !body.collisionResponse) {
  3969. return;
  3970. }
  3971. if ((this.collisionFilterGroup & body.collisionFilterMask) === 0 || (body.collisionFilterGroup & this.collisionFilterMask) === 0) {
  3972. return;
  3973. }
  3974. const xi = intersectBody_xi;
  3975. const qi = intersectBody_qi;
  3976. for (let i = 0, N = body.shapes.length; i < N; i++) {
  3977. const shape = body.shapes[i];
  3978. if (checkCollisionResponse && !shape.collisionResponse) {
  3979. continue; // Skip
  3980. }
  3981. body.quaternion.mult(body.shapeOrientations[i], qi);
  3982. body.quaternion.vmult(body.shapeOffsets[i], xi);
  3983. xi.vadd(body.position, xi);
  3984. this.intersectShape(shape, qi, xi, body);
  3985. if (this.result.shouldStop) {
  3986. break;
  3987. }
  3988. }
  3989. }
  3990. /**
  3991. * Shoot a ray at an array bodies, get back information about the hit.
  3992. * @param bodies An array of Body objects.
  3993. * @deprecated @param result set the result property of the Ray instead.
  3994. *
  3995. */
  3996. intersectBodies(bodies, result) {
  3997. if (result) {
  3998. this.result = result;
  3999. this.updateDirection();
  4000. }
  4001. for (let i = 0, l = bodies.length; !this.result.shouldStop && i < l; i++) {
  4002. this.intersectBody(bodies[i]);
  4003. }
  4004. }
  4005. /**
  4006. * Updates the direction vector.
  4007. */
  4008. updateDirection() {
  4009. this.to.vsub(this.from, this.direction);
  4010. this.direction.normalize();
  4011. }
  4012. intersectShape(shape, quat, position, body) {
  4013. const from = this.from; // Checking boundingSphere
  4014. const distance = distanceFromIntersection(from, this.direction, position);
  4015. if (distance > shape.boundingSphereRadius) {
  4016. return;
  4017. }
  4018. const intersectMethod = this[shape.type];
  4019. if (intersectMethod) {
  4020. intersectMethod.call(this, shape, quat, position, body, shape);
  4021. }
  4022. }
  4023. _intersectBox(box, quat, position, body, reportedShape) {
  4024. return this._intersectConvex(box.convexPolyhedronRepresentation, quat, position, body, reportedShape);
  4025. }
  4026. _intersectPlane(shape, quat, position, body, reportedShape) {
  4027. const from = this.from;
  4028. const to = this.to;
  4029. const direction = this.direction; // Get plane normal
  4030. const worldNormal = new Vec3(0, 0, 1);
  4031. quat.vmult(worldNormal, worldNormal);
  4032. const len = new Vec3();
  4033. from.vsub(position, len);
  4034. const planeToFrom = len.dot(worldNormal);
  4035. to.vsub(position, len);
  4036. const planeToTo = len.dot(worldNormal);
  4037. if (planeToFrom * planeToTo > 0) {
  4038. // "from" and "to" are on the same side of the plane... bail out
  4039. return;
  4040. }
  4041. if (from.distanceTo(to) < planeToFrom) {
  4042. return;
  4043. }
  4044. const n_dot_dir = worldNormal.dot(direction);
  4045. if (Math.abs(n_dot_dir) < this.precision) {
  4046. // No intersection
  4047. return;
  4048. }
  4049. const planePointToFrom = new Vec3();
  4050. const dir_scaled_with_t = new Vec3();
  4051. const hitPointWorld = new Vec3();
  4052. from.vsub(position, planePointToFrom);
  4053. const t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  4054. direction.scale(t, dir_scaled_with_t);
  4055. from.vadd(dir_scaled_with_t, hitPointWorld);
  4056. this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);
  4057. }
  4058. /**
  4059. * Get the world AABB of the ray.
  4060. */
  4061. getAABB(aabb) {
  4062. const {
  4063. lowerBound,
  4064. upperBound
  4065. } = aabb;
  4066. const to = this.to;
  4067. const from = this.from;
  4068. lowerBound.x = Math.min(to.x, from.x);
  4069. lowerBound.y = Math.min(to.y, from.y);
  4070. lowerBound.z = Math.min(to.z, from.z);
  4071. upperBound.x = Math.max(to.x, from.x);
  4072. upperBound.y = Math.max(to.y, from.y);
  4073. upperBound.z = Math.max(to.z, from.z);
  4074. }
  4075. _intersectHeightfield(shape, quat, position, body, reportedShape) {
  4076. shape.data;
  4077. shape.elementSize; // Convert the ray to local heightfield coordinates
  4078. const localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);
  4079. localRay.from.copy(this.from);
  4080. localRay.to.copy(this.to);
  4081. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  4082. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  4083. localRay.updateDirection(); // Get the index of the data points to test against
  4084. const index = intersectHeightfield_index;
  4085. let iMinX;
  4086. let iMinY;
  4087. let iMaxX;
  4088. let iMaxY; // Set to max
  4089. iMinX = iMinY = 0;
  4090. iMaxX = iMaxY = shape.data.length - 1;
  4091. const aabb = new AABB();
  4092. localRay.getAABB(aabb);
  4093. shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);
  4094. iMinX = Math.max(iMinX, index[0]);
  4095. iMinY = Math.max(iMinY, index[1]);
  4096. shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);
  4097. iMaxX = Math.min(iMaxX, index[0] + 1);
  4098. iMaxY = Math.min(iMaxY, index[1] + 1);
  4099. for (let i = iMinX; i < iMaxX; i++) {
  4100. for (let j = iMinY; j < iMaxY; j++) {
  4101. if (this.result.shouldStop) {
  4102. return;
  4103. }
  4104. shape.getAabbAtIndex(i, j, aabb);
  4105. if (!aabb.overlapsRay(localRay)) {
  4106. continue;
  4107. } // Lower triangle
  4108. shape.getConvexTrianglePillar(i, j, false);
  4109. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  4110. this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
  4111. if (this.result.shouldStop) {
  4112. return;
  4113. } // Upper triangle
  4114. shape.getConvexTrianglePillar(i, j, true);
  4115. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  4116. this._intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
  4117. }
  4118. }
  4119. }
  4120. _intersectSphere(sphere, quat, position, body, reportedShape) {
  4121. const from = this.from;
  4122. const to = this.to;
  4123. const r = sphere.radius;
  4124. const a = (to.x - from.x) ** 2 + (to.y - from.y) ** 2 + (to.z - from.z) ** 2;
  4125. const b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));
  4126. const c = (from.x - position.x) ** 2 + (from.y - position.y) ** 2 + (from.z - position.z) ** 2 - r ** 2;
  4127. const delta = b ** 2 - 4 * a * c;
  4128. const intersectionPoint = Ray_intersectSphere_intersectionPoint;
  4129. const normal = Ray_intersectSphere_normal;
  4130. if (delta < 0) {
  4131. // No intersection
  4132. return;
  4133. } else if (delta === 0) {
  4134. // single intersection point
  4135. from.lerp(to, delta, intersectionPoint);
  4136. intersectionPoint.vsub(position, normal);
  4137. normal.normalize();
  4138. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4139. } else {
  4140. const d1 = (-b - Math.sqrt(delta)) / (2 * a);
  4141. const d2 = (-b + Math.sqrt(delta)) / (2 * a);
  4142. if (d1 >= 0 && d1 <= 1) {
  4143. from.lerp(to, d1, intersectionPoint);
  4144. intersectionPoint.vsub(position, normal);
  4145. normal.normalize();
  4146. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4147. }
  4148. if (this.result.shouldStop) {
  4149. return;
  4150. }
  4151. if (d2 >= 0 && d2 <= 1) {
  4152. from.lerp(to, d2, intersectionPoint);
  4153. intersectionPoint.vsub(position, normal);
  4154. normal.normalize();
  4155. this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
  4156. }
  4157. }
  4158. }
  4159. _intersectConvex(shape, quat, position, body, reportedShape, options) {
  4160. const normal = intersectConvex_normal;
  4161. const vector = intersectConvex_vector;
  4162. const faceList = options && options.faceList || null; // Checking faces
  4163. const faces = shape.faces;
  4164. const vertices = shape.vertices;
  4165. const normals = shape.faceNormals;
  4166. const direction = this.direction;
  4167. const from = this.from;
  4168. const to = this.to;
  4169. const fromToDistance = from.distanceTo(to);
  4170. const Nfaces = faceList ? faceList.length : faces.length;
  4171. const result = this.result;
  4172. for (let j = 0; !result.shouldStop && j < Nfaces; j++) {
  4173. const fi = faceList ? faceList[j] : j;
  4174. const face = faces[fi];
  4175. const faceNormal = normals[fi];
  4176. const q = quat;
  4177. const x = position; // determine if ray intersects the plane of the face
  4178. // note: this works regardless of the direction of the face normal
  4179. // Get plane point in world coordinates...
  4180. vector.copy(vertices[face[0]]);
  4181. q.vmult(vector, vector);
  4182. vector.vadd(x, vector); // ...but make it relative to the ray from. We'll fix this later.
  4183. vector.vsub(from, vector); // Get plane normal
  4184. q.vmult(faceNormal, normal); // If this dot product is negative, we have something interesting
  4185. const dot = direction.dot(normal); // Bail out if ray and plane are parallel
  4186. if (Math.abs(dot) < this.precision) {
  4187. continue;
  4188. } // calc distance to plane
  4189. const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray
  4190. if (scalar < 0) {
  4191. continue;
  4192. } // if (dot < 0) {
  4193. // Intersection point is from + direction * scalar
  4194. direction.scale(scalar, intersectPoint);
  4195. intersectPoint.vadd(from, intersectPoint); // a is the point we compare points b and c with.
  4196. a.copy(vertices[face[0]]);
  4197. q.vmult(a, a);
  4198. x.vadd(a, a);
  4199. for (let i = 1; !result.shouldStop && i < face.length - 1; i++) {
  4200. // Transform 3 vertices to world coords
  4201. b.copy(vertices[face[i]]);
  4202. c.copy(vertices[face[i + 1]]);
  4203. q.vmult(b, b);
  4204. q.vmult(c, c);
  4205. x.vadd(b, b);
  4206. x.vadd(c, c);
  4207. const distance = intersectPoint.distanceTo(from);
  4208. if (!(Ray.pointInTriangle(intersectPoint, a, b, c) || Ray.pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance) {
  4209. continue;
  4210. }
  4211. this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);
  4212. } // }
  4213. }
  4214. }
  4215. /**
  4216. * @todo Optimize by transforming the world to local space first.
  4217. * @todo Use Octree lookup
  4218. */
  4219. _intersectTrimesh(mesh, quat, position, body, reportedShape, options) {
  4220. const normal = intersectTrimesh_normal;
  4221. const triangles = intersectTrimesh_triangles;
  4222. const treeTransform = intersectTrimesh_treeTransform;
  4223. const vector = intersectConvex_vector;
  4224. const localDirection = intersectTrimesh_localDirection;
  4225. const localFrom = intersectTrimesh_localFrom;
  4226. const localTo = intersectTrimesh_localTo;
  4227. const worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  4228. const worldNormal = intersectTrimesh_worldNormal; // Checking faces
  4229. const indices = mesh.indices;
  4230. mesh.vertices; // const normals = mesh.faceNormals
  4231. const from = this.from;
  4232. const to = this.to;
  4233. const direction = this.direction;
  4234. treeTransform.position.copy(position);
  4235. treeTransform.quaternion.copy(quat); // Transform ray to local space!
  4236. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  4237. Transform.pointToLocalFrame(position, quat, from, localFrom);
  4238. Transform.pointToLocalFrame(position, quat, to, localTo);
  4239. localTo.x *= mesh.scale.x;
  4240. localTo.y *= mesh.scale.y;
  4241. localTo.z *= mesh.scale.z;
  4242. localFrom.x *= mesh.scale.x;
  4243. localFrom.y *= mesh.scale.y;
  4244. localFrom.z *= mesh.scale.z;
  4245. localTo.vsub(localFrom, localDirection);
  4246. localDirection.normalize();
  4247. const fromToDistanceSquared = localFrom.distanceSquared(localTo);
  4248. mesh.tree.rayQuery(this, treeTransform, triangles);
  4249. for (let i = 0, N = triangles.length; !this.result.shouldStop && i !== N; i++) {
  4250. const trianglesIndex = triangles[i];
  4251. mesh.getNormal(trianglesIndex, normal); // determine if ray intersects the plane of the face
  4252. // note: this works regardless of the direction of the face normal
  4253. // Get plane point in world coordinates...
  4254. mesh.getVertex(indices[trianglesIndex * 3], a); // ...but make it relative to the ray from. We'll fix this later.
  4255. a.vsub(localFrom, vector); // If this dot product is negative, we have something interesting
  4256. const dot = localDirection.dot(normal); // Bail out if ray and plane are parallel
  4257. // if (Math.abs( dot ) < this.precision){
  4258. // continue;
  4259. // }
  4260. // calc distance to plane
  4261. const scalar = normal.dot(vector) / dot; // if negative distance, then plane is behind ray
  4262. if (scalar < 0) {
  4263. continue;
  4264. } // Intersection point is from + direction * scalar
  4265. localDirection.scale(scalar, intersectPoint);
  4266. intersectPoint.vadd(localFrom, intersectPoint); // Get triangle vertices
  4267. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  4268. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  4269. const squaredDistance = intersectPoint.distanceSquared(localFrom);
  4270. if (!(Ray.pointInTriangle(intersectPoint, b, a, c) || Ray.pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared) {
  4271. continue;
  4272. } // transform intersectpoint and normal to world
  4273. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  4274. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  4275. this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);
  4276. }
  4277. triangles.length = 0;
  4278. }
  4279. /**
  4280. * @return True if the intersections should continue
  4281. */
  4282. reportIntersection(normal, hitPointWorld, shape, body, hitFaceIndex) {
  4283. const from = this.from;
  4284. const to = this.to;
  4285. const distance = from.distanceTo(hitPointWorld);
  4286. const result = this.result; // Skip back faces?
  4287. if (this.skipBackfaces && normal.dot(this.direction) > 0) {
  4288. return;
  4289. }
  4290. result.hitFaceIndex = typeof hitFaceIndex !== 'undefined' ? hitFaceIndex : -1;
  4291. switch (this.mode) {
  4292. case Ray.ALL:
  4293. this.hasHit = true;
  4294. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4295. result.hasHit = true;
  4296. this.callback(result);
  4297. break;
  4298. case Ray.CLOSEST:
  4299. // Store if closer than current closest
  4300. if (distance < result.distance || !result.hasHit) {
  4301. this.hasHit = true;
  4302. result.hasHit = true;
  4303. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4304. }
  4305. break;
  4306. case Ray.ANY:
  4307. // Report and stop.
  4308. this.hasHit = true;
  4309. result.hasHit = true;
  4310. result.set(from, to, normal, hitPointWorld, shape, body, distance);
  4311. result.shouldStop = true;
  4312. break;
  4313. }
  4314. }
  4315. /**
  4316. * As per "Barycentric Technique" as named
  4317. * {@link https://www.blackpawn.com/texts/pointinpoly/default.html here} but without the division
  4318. */
  4319. static pointInTriangle(p, a, b, c) {
  4320. c.vsub(a, v0);
  4321. b.vsub(a, v1);
  4322. p.vsub(a, v2);
  4323. const dot00 = v0.dot(v0);
  4324. const dot01 = v0.dot(v1);
  4325. const dot02 = v0.dot(v2);
  4326. const dot11 = v1.dot(v1);
  4327. const dot12 = v1.dot(v2);
  4328. let u;
  4329. let v;
  4330. return (u = dot11 * dot02 - dot01 * dot12) >= 0 && (v = dot00 * dot12 - dot01 * dot02) >= 0 && u + v < dot00 * dot11 - dot01 * dot01;
  4331. }
  4332. }
  4333. Ray.CLOSEST = RAY_MODES.CLOSEST;
  4334. Ray.ANY = RAY_MODES.ANY;
  4335. Ray.ALL = RAY_MODES.ALL;
  4336. const tmpAABB$1 = new AABB();
  4337. const tmpArray = [];
  4338. const v1 = new Vec3();
  4339. const v2 = new Vec3();
  4340. const intersectBody_xi = new Vec3();
  4341. const intersectBody_qi = new Quaternion();
  4342. const intersectPoint = new Vec3();
  4343. const a = new Vec3();
  4344. const b = new Vec3();
  4345. const c = new Vec3();
  4346. const intersectConvexOptions = {
  4347. faceList: [0]
  4348. };
  4349. const worldPillarOffset = new Vec3();
  4350. const intersectHeightfield_localRay = new Ray();
  4351. const intersectHeightfield_index = [];
  4352. const Ray_intersectSphere_intersectionPoint = new Vec3();
  4353. const Ray_intersectSphere_normal = new Vec3();
  4354. const intersectConvex_normal = new Vec3();
  4355. const intersectConvex_vector = new Vec3();
  4356. const intersectTrimesh_normal = new Vec3();
  4357. const intersectTrimesh_localDirection = new Vec3();
  4358. const intersectTrimesh_localFrom = new Vec3();
  4359. const intersectTrimesh_localTo = new Vec3();
  4360. const intersectTrimesh_worldNormal = new Vec3();
  4361. const intersectTrimesh_worldIntersectPoint = new Vec3();
  4362. new AABB();
  4363. const intersectTrimesh_triangles = [];
  4364. const intersectTrimesh_treeTransform = new Transform();
  4365. const v0 = new Vec3();
  4366. const intersect = new Vec3();
  4367. function distanceFromIntersection(from, direction, position) {
  4368. // v0 is vector from from to position
  4369. position.vsub(from, v0);
  4370. const dot = v0.dot(direction); // intersect = direction*dot + from
  4371. direction.scale(dot, intersect);
  4372. intersect.vadd(from, intersect);
  4373. const distance = position.distanceTo(intersect);
  4374. return distance;
  4375. }
  4376. /**
  4377. * Sweep and prune broadphase along one axis.
  4378. */
  4379. class SAPBroadphase extends Broadphase {
  4380. /**
  4381. * List of bodies currently in the broadphase.
  4382. */
  4383. /**
  4384. * The world to search in.
  4385. */
  4386. /**
  4387. * Axis to sort the bodies along.
  4388. * Set to 0 for x axis, and 1 for y axis.
  4389. * For best performance, pick the axis where bodies are most distributed.
  4390. */
  4391. /**
  4392. * Check if the bounds of two bodies overlap, along the given SAP axis.
  4393. */
  4394. static checkBounds(bi, bj, axisIndex) {
  4395. let biPos;
  4396. let bjPos;
  4397. if (axisIndex === 0) {
  4398. biPos = bi.position.x;
  4399. bjPos = bj.position.x;
  4400. } else if (axisIndex === 1) {
  4401. biPos = bi.position.y;
  4402. bjPos = bj.position.y;
  4403. } else if (axisIndex === 2) {
  4404. biPos = bi.position.z;
  4405. bjPos = bj.position.z;
  4406. }
  4407. const ri = bi.boundingRadius,
  4408. rj = bj.boundingRadius,
  4409. boundA2 = biPos + ri,
  4410. boundB1 = bjPos - rj;
  4411. return boundB1 < boundA2;
  4412. } // Note: these are identical, save for x/y/z lowerbound
  4413. /**
  4414. * insertionSortX
  4415. */
  4416. static insertionSortX(a) {
  4417. for (let i = 1, l = a.length; i < l; i++) {
  4418. const v = a[i];
  4419. let j;
  4420. for (j = i - 1; j >= 0; j--) {
  4421. if (a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x) {
  4422. break;
  4423. }
  4424. a[j + 1] = a[j];
  4425. }
  4426. a[j + 1] = v;
  4427. }
  4428. return a;
  4429. }
  4430. /**
  4431. * insertionSortY
  4432. */
  4433. static insertionSortY(a) {
  4434. for (let i = 1, l = a.length; i < l; i++) {
  4435. const v = a[i];
  4436. let j;
  4437. for (j = i - 1; j >= 0; j--) {
  4438. if (a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y) {
  4439. break;
  4440. }
  4441. a[j + 1] = a[j];
  4442. }
  4443. a[j + 1] = v;
  4444. }
  4445. return a;
  4446. }
  4447. /**
  4448. * insertionSortZ
  4449. */
  4450. static insertionSortZ(a) {
  4451. for (let i = 1, l = a.length; i < l; i++) {
  4452. const v = a[i];
  4453. let j;
  4454. for (j = i - 1; j >= 0; j--) {
  4455. if (a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z) {
  4456. break;
  4457. }
  4458. a[j + 1] = a[j];
  4459. }
  4460. a[j + 1] = v;
  4461. }
  4462. return a;
  4463. }
  4464. constructor(world) {
  4465. super();
  4466. this.axisList = void 0;
  4467. this.world = void 0;
  4468. this.axisIndex = void 0;
  4469. this._addBodyHandler = void 0;
  4470. this._removeBodyHandler = void 0;
  4471. this.axisList = [];
  4472. this.world = null;
  4473. this.axisIndex = 0;
  4474. const axisList = this.axisList;
  4475. this._addBodyHandler = event => {
  4476. axisList.push(event.body);
  4477. };
  4478. this._removeBodyHandler = event => {
  4479. const idx = axisList.indexOf(event.body);
  4480. if (idx !== -1) {
  4481. axisList.splice(idx, 1);
  4482. }
  4483. };
  4484. if (world) {
  4485. this.setWorld(world);
  4486. }
  4487. }
  4488. /**
  4489. * Change the world
  4490. */
  4491. setWorld(world) {
  4492. // Clear the old axis array
  4493. this.axisList.length = 0; // Add all bodies from the new world
  4494. for (let i = 0; i < world.bodies.length; i++) {
  4495. this.axisList.push(world.bodies[i]);
  4496. } // Remove old handlers, if any
  4497. world.removeEventListener('addBody', this._addBodyHandler);
  4498. world.removeEventListener('removeBody', this._removeBodyHandler); // Add handlers to update the list of bodies.
  4499. world.addEventListener('addBody', this._addBodyHandler);
  4500. world.addEventListener('removeBody', this._removeBodyHandler);
  4501. this.world = world;
  4502. this.dirty = true;
  4503. }
  4504. /**
  4505. * Collect all collision pairs
  4506. */
  4507. collisionPairs(world, p1, p2) {
  4508. const bodies = this.axisList;
  4509. const N = bodies.length;
  4510. const axisIndex = this.axisIndex;
  4511. let i;
  4512. let j;
  4513. if (this.dirty) {
  4514. this.sortList();
  4515. this.dirty = false;
  4516. } // Look through the list
  4517. for (i = 0; i !== N; i++) {
  4518. const bi = bodies[i];
  4519. for (j = i + 1; j < N; j++) {
  4520. const bj = bodies[j];
  4521. if (!this.needBroadphaseCollision(bi, bj)) {
  4522. continue;
  4523. }
  4524. if (!SAPBroadphase.checkBounds(bi, bj, axisIndex)) {
  4525. break;
  4526. }
  4527. this.intersectionTest(bi, bj, p1, p2);
  4528. }
  4529. }
  4530. }
  4531. sortList() {
  4532. const axisList = this.axisList;
  4533. const axisIndex = this.axisIndex;
  4534. const N = axisList.length; // Update AABBs
  4535. for (let i = 0; i !== N; i++) {
  4536. const bi = axisList[i];
  4537. if (bi.aabbNeedsUpdate) {
  4538. bi.updateAABB();
  4539. }
  4540. } // Sort the list
  4541. if (axisIndex === 0) {
  4542. SAPBroadphase.insertionSortX(axisList);
  4543. } else if (axisIndex === 1) {
  4544. SAPBroadphase.insertionSortY(axisList);
  4545. } else if (axisIndex === 2) {
  4546. SAPBroadphase.insertionSortZ(axisList);
  4547. }
  4548. }
  4549. /**
  4550. * Computes the variance of the body positions and estimates the best axis to use.
  4551. * Will automatically set property `axisIndex`.
  4552. */
  4553. autoDetectAxis() {
  4554. let sumX = 0;
  4555. let sumX2 = 0;
  4556. let sumY = 0;
  4557. let sumY2 = 0;
  4558. let sumZ = 0;
  4559. let sumZ2 = 0;
  4560. const bodies = this.axisList;
  4561. const N = bodies.length;
  4562. const invN = 1 / N;
  4563. for (let i = 0; i !== N; i++) {
  4564. const b = bodies[i];
  4565. const centerX = b.position.x;
  4566. sumX += centerX;
  4567. sumX2 += centerX * centerX;
  4568. const centerY = b.position.y;
  4569. sumY += centerY;
  4570. sumY2 += centerY * centerY;
  4571. const centerZ = b.position.z;
  4572. sumZ += centerZ;
  4573. sumZ2 += centerZ * centerZ;
  4574. }
  4575. const varianceX = sumX2 - sumX * sumX * invN;
  4576. const varianceY = sumY2 - sumY * sumY * invN;
  4577. const varianceZ = sumZ2 - sumZ * sumZ * invN;
  4578. if (varianceX > varianceY) {
  4579. if (varianceX > varianceZ) {
  4580. this.axisIndex = 0;
  4581. } else {
  4582. this.axisIndex = 2;
  4583. }
  4584. } else if (varianceY > varianceZ) {
  4585. this.axisIndex = 1;
  4586. } else {
  4587. this.axisIndex = 2;
  4588. }
  4589. }
  4590. /**
  4591. * Returns all the bodies within an AABB.
  4592. * @param result An array to store resulting bodies in.
  4593. */
  4594. aabbQuery(world, aabb, result = []) {
  4595. if (this.dirty) {
  4596. this.sortList();
  4597. this.dirty = false;
  4598. }
  4599. const axisIndex = this.axisIndex;
  4600. let axis = 'x';
  4601. if (axisIndex === 1) {
  4602. axis = 'y';
  4603. }
  4604. if (axisIndex === 2) {
  4605. axis = 'z';
  4606. }
  4607. const axisList = this.axisList;
  4608. aabb.lowerBound[axis];
  4609. aabb.upperBound[axis];
  4610. for (let i = 0; i < axisList.length; i++) {
  4611. const b = axisList[i];
  4612. if (b.aabbNeedsUpdate) {
  4613. b.updateAABB();
  4614. }
  4615. if (b.aabb.overlaps(aabb)) {
  4616. result.push(b);
  4617. }
  4618. }
  4619. return result;
  4620. }
  4621. }
  4622. class Utils {
  4623. /**
  4624. * Extend an options object with default values.
  4625. * @param options The options object. May be falsy: in this case, a new object is created and returned.
  4626. * @param defaults An object containing default values.
  4627. * @return The modified options object.
  4628. */
  4629. static defaults(options = {}, defaults) {
  4630. for (let key in defaults) {
  4631. if (!(key in options)) {
  4632. options[key] = defaults[key];
  4633. }
  4634. }
  4635. return options;
  4636. }
  4637. }
  4638. /**
  4639. * Constraint base class
  4640. */
  4641. class Constraint {
  4642. /**
  4643. * Equations to be solved in this constraint.
  4644. */
  4645. /**
  4646. * Body A.
  4647. */
  4648. /**
  4649. * Body B.
  4650. */
  4651. /**
  4652. * Set to false if you don't want the bodies to collide when they are connected.
  4653. */
  4654. constructor(bodyA, bodyB, options = {}) {
  4655. this.equations = void 0;
  4656. this.bodyA = void 0;
  4657. this.bodyB = void 0;
  4658. this.id = void 0;
  4659. this.collideConnected = void 0;
  4660. options = Utils.defaults(options, {
  4661. collideConnected: true,
  4662. wakeUpBodies: true
  4663. });
  4664. this.equations = [];
  4665. this.bodyA = bodyA;
  4666. this.bodyB = bodyB;
  4667. this.id = Constraint.idCounter++;
  4668. this.collideConnected = options.collideConnected;
  4669. if (options.wakeUpBodies) {
  4670. if (bodyA) {
  4671. bodyA.wakeUp();
  4672. }
  4673. if (bodyB) {
  4674. bodyB.wakeUp();
  4675. }
  4676. }
  4677. }
  4678. /**
  4679. * Update all the equations with data.
  4680. */
  4681. update() {
  4682. throw new Error('method update() not implmemented in this Constraint subclass!');
  4683. }
  4684. /**
  4685. * Enables all equations in the constraint.
  4686. */
  4687. enable() {
  4688. const eqs = this.equations;
  4689. for (let i = 0; i < eqs.length; i++) {
  4690. eqs[i].enabled = true;
  4691. }
  4692. }
  4693. /**
  4694. * Disables all equations in the constraint.
  4695. */
  4696. disable() {
  4697. const eqs = this.equations;
  4698. for (let i = 0; i < eqs.length; i++) {
  4699. eqs[i].enabled = false;
  4700. }
  4701. }
  4702. }
  4703. Constraint.idCounter = 0;
  4704. /**
  4705. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  4706. */
  4707. class JacobianElement {
  4708. /**
  4709. * spatial
  4710. */
  4711. /**
  4712. * rotational
  4713. */
  4714. constructor() {
  4715. this.spatial = void 0;
  4716. this.rotational = void 0;
  4717. this.spatial = new Vec3();
  4718. this.rotational = new Vec3();
  4719. }
  4720. /**
  4721. * Multiply with other JacobianElement
  4722. */
  4723. multiplyElement(element) {
  4724. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  4725. }
  4726. /**
  4727. * Multiply with two vectors
  4728. */
  4729. multiplyVectors(spatial, rotational) {
  4730. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  4731. }
  4732. }
  4733. /**
  4734. * Equation base class.
  4735. *
  4736. * `a`, `b` and `eps` are {@link https://www8.cs.umu.se/kurser/5DV058/VT15/lectures/SPOOKlabnotes.pdf SPOOK} parameters that default to `0.0`. See {@link https://github.com/schteppe/cannon.js/issues/238#issuecomment-147172327 this exchange} for more details on Cannon's physics implementation.
  4737. */
  4738. class Equation {
  4739. /**
  4740. * Minimum (read: negative max) force to be applied by the constraint.
  4741. */
  4742. /**
  4743. * Maximum (read: positive max) force to be applied by the constraint.
  4744. */
  4745. /**
  4746. * SPOOK parameter
  4747. */
  4748. /**
  4749. * SPOOK parameter
  4750. */
  4751. /**
  4752. * SPOOK parameter
  4753. */
  4754. /**
  4755. * A number, proportional to the force added to the bodies.
  4756. */
  4757. constructor(bi, bj, minForce = -1e6, maxForce = 1e6) {
  4758. this.id = void 0;
  4759. this.minForce = void 0;
  4760. this.maxForce = void 0;
  4761. this.bi = void 0;
  4762. this.bj = void 0;
  4763. this.si = void 0;
  4764. this.sj = void 0;
  4765. this.a = void 0;
  4766. this.b = void 0;
  4767. this.eps = void 0;
  4768. this.jacobianElementA = void 0;
  4769. this.jacobianElementB = void 0;
  4770. this.enabled = void 0;
  4771. this.multiplier = void 0;
  4772. this.id = Equation.idCounter++;
  4773. this.minForce = minForce;
  4774. this.maxForce = maxForce;
  4775. this.bi = bi;
  4776. this.bj = bj;
  4777. this.a = 0.0; // SPOOK parameter
  4778. this.b = 0.0; // SPOOK parameter
  4779. this.eps = 0.0; // SPOOK parameter
  4780. this.jacobianElementA = new JacobianElement();
  4781. this.jacobianElementB = new JacobianElement();
  4782. this.enabled = true;
  4783. this.multiplier = 0;
  4784. this.setSpookParams(1e7, 4, 1 / 60); // Set typical spook params
  4785. }
  4786. /**
  4787. * Recalculates a, b, and eps.
  4788. *
  4789. * The Equation constructor sets typical SPOOK parameters as such:
  4790. * * `stiffness` = 1e7
  4791. * * `relaxation` = 4
  4792. * * `timeStep`= 1 / 60, _note the hardcoded refresh rate._
  4793. */
  4794. setSpookParams(stiffness, relaxation, timeStep) {
  4795. const d = relaxation;
  4796. const k = stiffness;
  4797. const h = timeStep;
  4798. this.a = 4.0 / (h * (1 + 4 * d));
  4799. this.b = 4.0 * d / (1 + 4 * d);
  4800. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  4801. }
  4802. /**
  4803. * Computes the right hand side of the SPOOK equation
  4804. */
  4805. computeB(a, b, h) {
  4806. const GW = this.computeGW();
  4807. const Gq = this.computeGq();
  4808. const GiMf = this.computeGiMf();
  4809. return -Gq * a - GW * b - GiMf * h;
  4810. }
  4811. /**
  4812. * Computes G*q, where q are the generalized body coordinates
  4813. */
  4814. computeGq() {
  4815. const GA = this.jacobianElementA;
  4816. const GB = this.jacobianElementB;
  4817. const bi = this.bi;
  4818. const bj = this.bj;
  4819. const xi = bi.position;
  4820. const xj = bj.position;
  4821. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  4822. }
  4823. /**
  4824. * Computes G*W, where W are the body velocities
  4825. */
  4826. computeGW() {
  4827. const GA = this.jacobianElementA;
  4828. const GB = this.jacobianElementB;
  4829. const bi = this.bi;
  4830. const bj = this.bj;
  4831. const vi = bi.velocity;
  4832. const vj = bj.velocity;
  4833. const wi = bi.angularVelocity;
  4834. const wj = bj.angularVelocity;
  4835. return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  4836. }
  4837. /**
  4838. * Computes G*Wlambda, where W are the body velocities
  4839. */
  4840. computeGWlambda() {
  4841. const GA = this.jacobianElementA;
  4842. const GB = this.jacobianElementB;
  4843. const bi = this.bi;
  4844. const bj = this.bj;
  4845. const vi = bi.vlambda;
  4846. const vj = bj.vlambda;
  4847. const wi = bi.wlambda;
  4848. const wj = bj.wlambda;
  4849. return GA.multiplyVectors(vi, wi) + GB.multiplyVectors(vj, wj);
  4850. }
  4851. /**
  4852. * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
  4853. */
  4854. computeGiMf() {
  4855. const GA = this.jacobianElementA;
  4856. const GB = this.jacobianElementB;
  4857. const bi = this.bi;
  4858. const bj = this.bj;
  4859. const fi = bi.force;
  4860. const ti = bi.torque;
  4861. const fj = bj.force;
  4862. const tj = bj.torque;
  4863. const invMassi = bi.invMassSolve;
  4864. const invMassj = bj.invMassSolve;
  4865. fi.scale(invMassi, iMfi);
  4866. fj.scale(invMassj, iMfj);
  4867. bi.invInertiaWorldSolve.vmult(ti, invIi_vmult_taui);
  4868. bj.invInertiaWorldSolve.vmult(tj, invIj_vmult_tauj);
  4869. return GA.multiplyVectors(iMfi, invIi_vmult_taui) + GB.multiplyVectors(iMfj, invIj_vmult_tauj);
  4870. }
  4871. /**
  4872. * Computes G*inv(M)*G'
  4873. */
  4874. computeGiMGt() {
  4875. const GA = this.jacobianElementA;
  4876. const GB = this.jacobianElementB;
  4877. const bi = this.bi;
  4878. const bj = this.bj;
  4879. const invMassi = bi.invMassSolve;
  4880. const invMassj = bj.invMassSolve;
  4881. const invIi = bi.invInertiaWorldSolve;
  4882. const invIj = bj.invInertiaWorldSolve;
  4883. let result = invMassi + invMassj;
  4884. invIi.vmult(GA.rotational, tmp);
  4885. result += tmp.dot(GA.rotational);
  4886. invIj.vmult(GB.rotational, tmp);
  4887. result += tmp.dot(GB.rotational);
  4888. return result;
  4889. }
  4890. /**
  4891. * Add constraint velocity to the bodies.
  4892. */
  4893. addToWlambda(deltalambda) {
  4894. const GA = this.jacobianElementA;
  4895. const GB = this.jacobianElementB;
  4896. const bi = this.bi;
  4897. const bj = this.bj;
  4898. const temp = addToWlambda_temp; // Add to linear velocity
  4899. // v_lambda += inv(M) * delta_lamba * G
  4900. bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);
  4901. bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda); // Add to angular velocity
  4902. bi.invInertiaWorldSolve.vmult(GA.rotational, temp);
  4903. bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);
  4904. bj.invInertiaWorldSolve.vmult(GB.rotational, temp);
  4905. bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);
  4906. }
  4907. /**
  4908. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  4909. */
  4910. computeC() {
  4911. return this.computeGiMGt() + this.eps;
  4912. }
  4913. }
  4914. Equation.idCounter = 0;
  4915. const iMfi = new Vec3();
  4916. const iMfj = new Vec3();
  4917. const invIi_vmult_taui = new Vec3();
  4918. const invIj_vmult_tauj = new Vec3();
  4919. const tmp = new Vec3();
  4920. const addToWlambda_temp = new Vec3();
  4921. /**
  4922. * Contact/non-penetration constraint equation
  4923. */
  4924. class ContactEquation extends Equation {
  4925. /**
  4926. * "bounciness": u1 = -e*u0
  4927. */
  4928. /**
  4929. * World-oriented vector that goes from the center of bi to the contact point.
  4930. */
  4931. /**
  4932. * World-oriented vector that starts in body j position and goes to the contact point.
  4933. */
  4934. /**
  4935. * Contact normal, pointing out of body i.
  4936. */
  4937. constructor(bodyA, bodyB, maxForce = 1e6) {
  4938. super(bodyA, bodyB, 0, maxForce);
  4939. this.restitution = void 0;
  4940. this.ri = void 0;
  4941. this.rj = void 0;
  4942. this.ni = void 0;
  4943. this.restitution = 0.0;
  4944. this.ri = new Vec3();
  4945. this.rj = new Vec3();
  4946. this.ni = new Vec3();
  4947. }
  4948. computeB(h) {
  4949. const a = this.a;
  4950. const b = this.b;
  4951. const bi = this.bi;
  4952. const bj = this.bj;
  4953. const ri = this.ri;
  4954. const rj = this.rj;
  4955. const rixn = ContactEquation_computeB_temp1;
  4956. const rjxn = ContactEquation_computeB_temp2;
  4957. const vi = bi.velocity;
  4958. const wi = bi.angularVelocity;
  4959. bi.force;
  4960. bi.torque;
  4961. const vj = bj.velocity;
  4962. const wj = bj.angularVelocity;
  4963. bj.force;
  4964. bj.torque;
  4965. const penetrationVec = ContactEquation_computeB_temp3;
  4966. const GA = this.jacobianElementA;
  4967. const GB = this.jacobianElementB;
  4968. const n = this.ni; // Caluclate cross products
  4969. ri.cross(n, rixn);
  4970. rj.cross(n, rjxn); // g = xj+rj -(xi+ri)
  4971. // G = [ -ni -rixn ni rjxn ]
  4972. n.negate(GA.spatial);
  4973. rixn.negate(GA.rotational);
  4974. GB.spatial.copy(n);
  4975. GB.rotational.copy(rjxn); // Calculate the penetration vector
  4976. penetrationVec.copy(bj.position);
  4977. penetrationVec.vadd(rj, penetrationVec);
  4978. penetrationVec.vsub(bi.position, penetrationVec);
  4979. penetrationVec.vsub(ri, penetrationVec);
  4980. const g = n.dot(penetrationVec); // Compute iteration
  4981. const ePlusOne = this.restitution + 1;
  4982. const GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  4983. const GiMf = this.computeGiMf();
  4984. const B = -g * a - GW * b - h * GiMf;
  4985. return B;
  4986. }
  4987. /**
  4988. * Get the current relative velocity in the contact point.
  4989. */
  4990. getImpactVelocityAlongNormal() {
  4991. const vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  4992. const vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  4993. const xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  4994. const xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  4995. const relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  4996. this.bi.position.vadd(this.ri, xi);
  4997. this.bj.position.vadd(this.rj, xj);
  4998. this.bi.getVelocityAtWorldPoint(xi, vi);
  4999. this.bj.getVelocityAtWorldPoint(xj, vj);
  5000. vi.vsub(vj, relVel);
  5001. return this.ni.dot(relVel);
  5002. }
  5003. }
  5004. const ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  5005. const ContactEquation_computeB_temp2 = new Vec3();
  5006. const ContactEquation_computeB_temp3 = new Vec3();
  5007. const ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  5008. const ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  5009. const ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  5010. const ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  5011. const ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  5012. /**
  5013. * Connects two bodies at given offset points.
  5014. * @example
  5015. * const bodyA = new Body({ mass: 1 })
  5016. * const bodyB = new Body({ mass: 1 })
  5017. * bodyA.position.set(-1, 0, 0)
  5018. * bodyB.position.set(1, 0, 0)
  5019. * bodyA.addShape(shapeA)
  5020. * bodyB.addShape(shapeB)
  5021. * world.addBody(bodyA)
  5022. * world.addBody(bodyB)
  5023. * const localPivotA = new Vec3(1, 0, 0)
  5024. * const localPivotB = new Vec3(-1, 0, 0)
  5025. * const constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB)
  5026. * world.addConstraint(constraint)
  5027. */
  5028. class PointToPointConstraint extends Constraint {
  5029. /**
  5030. * Pivot, defined locally in bodyA.
  5031. */
  5032. /**
  5033. * Pivot, defined locally in bodyB.
  5034. */
  5035. /**
  5036. * @param pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  5037. * @param bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
  5038. * @param pivotB The point relative to the center of mass of bodyB which bodyB is constrained to.
  5039. * @param maxForce The maximum force that should be applied to constrain the bodies.
  5040. */
  5041. constructor(bodyA, pivotA = new Vec3(), bodyB, pivotB = new Vec3(), maxForce = 1e6) {
  5042. super(bodyA, bodyB);
  5043. this.pivotA = void 0;
  5044. this.pivotB = void 0;
  5045. this.equationX = void 0;
  5046. this.equationY = void 0;
  5047. this.equationZ = void 0;
  5048. this.pivotA = pivotA.clone();
  5049. this.pivotB = pivotB.clone();
  5050. const x = this.equationX = new ContactEquation(bodyA, bodyB);
  5051. const y = this.equationY = new ContactEquation(bodyA, bodyB);
  5052. const z = this.equationZ = new ContactEquation(bodyA, bodyB); // Equations to be fed to the solver
  5053. this.equations.push(x, y, z); // Make the equations bidirectional
  5054. x.minForce = y.minForce = z.minForce = -maxForce;
  5055. x.maxForce = y.maxForce = z.maxForce = maxForce;
  5056. x.ni.set(1, 0, 0);
  5057. y.ni.set(0, 1, 0);
  5058. z.ni.set(0, 0, 1);
  5059. }
  5060. update() {
  5061. const bodyA = this.bodyA;
  5062. const bodyB = this.bodyB;
  5063. const x = this.equationX;
  5064. const y = this.equationY;
  5065. const z = this.equationZ; // Rotate the pivots to world space
  5066. bodyA.quaternion.vmult(this.pivotA, x.ri);
  5067. bodyB.quaternion.vmult(this.pivotB, x.rj);
  5068. y.ri.copy(x.ri);
  5069. y.rj.copy(x.rj);
  5070. z.ri.copy(x.ri);
  5071. z.rj.copy(x.rj);
  5072. }
  5073. }
  5074. /**
  5075. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  5076. */
  5077. class ConeEquation extends Equation {
  5078. /**
  5079. * Local axis in A
  5080. */
  5081. /**
  5082. * Local axis in B
  5083. */
  5084. /**
  5085. * The "cone angle" to keep
  5086. */
  5087. constructor(bodyA, bodyB, options = {}) {
  5088. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5089. super(bodyA, bodyB, -maxForce, maxForce);
  5090. this.axisA = void 0;
  5091. this.axisB = void 0;
  5092. this.angle = void 0;
  5093. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5094. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  5095. this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  5096. }
  5097. computeB(h) {
  5098. const a = this.a;
  5099. const b = this.b;
  5100. const ni = this.axisA;
  5101. const nj = this.axisB;
  5102. const nixnj = tmpVec1$2;
  5103. const njxni = tmpVec2$2;
  5104. const GA = this.jacobianElementA;
  5105. const GB = this.jacobianElementB; // Caluclate cross products
  5106. ni.cross(nj, nixnj);
  5107. nj.cross(ni, njxni); // The angle between two vector is:
  5108. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  5109. // g = a * b
  5110. // gdot = (b x a) * wi + (a x b) * wj
  5111. // G = [0 bxa 0 axb]
  5112. // W = [vi wi vj wj]
  5113. GA.rotational.copy(njxni);
  5114. GB.rotational.copy(nixnj);
  5115. const g = Math.cos(this.angle) - ni.dot(nj);
  5116. const GW = this.computeGW();
  5117. const GiMf = this.computeGiMf();
  5118. const B = -g * a - GW * b - h * GiMf;
  5119. return B;
  5120. }
  5121. }
  5122. const tmpVec1$2 = new Vec3();
  5123. const tmpVec2$2 = new Vec3();
  5124. /**
  5125. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  5126. */
  5127. class RotationalEquation extends Equation {
  5128. /**
  5129. * World oriented rotational axis.
  5130. */
  5131. /**
  5132. * World oriented rotational axis.
  5133. */
  5134. /**
  5135. * maxAngle
  5136. */
  5137. constructor(bodyA, bodyB, options = {}) {
  5138. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5139. super(bodyA, bodyB, -maxForce, maxForce);
  5140. this.axisA = void 0;
  5141. this.axisB = void 0;
  5142. this.maxAngle = void 0;
  5143. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5144. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  5145. this.maxAngle = Math.PI / 2;
  5146. }
  5147. computeB(h) {
  5148. const a = this.a;
  5149. const b = this.b;
  5150. const ni = this.axisA;
  5151. const nj = this.axisB;
  5152. const nixnj = tmpVec1$1;
  5153. const njxni = tmpVec2$1;
  5154. const GA = this.jacobianElementA;
  5155. const GB = this.jacobianElementB; // Caluclate cross products
  5156. ni.cross(nj, nixnj);
  5157. nj.cross(ni, njxni); // g = ni * nj
  5158. // gdot = (nj x ni) * wi + (ni x nj) * wj
  5159. // G = [0 njxni 0 nixnj]
  5160. // W = [vi wi vj wj]
  5161. GA.rotational.copy(njxni);
  5162. GB.rotational.copy(nixnj);
  5163. const g = Math.cos(this.maxAngle) - ni.dot(nj);
  5164. const GW = this.computeGW();
  5165. const GiMf = this.computeGiMf();
  5166. const B = -g * a - GW * b - h * GiMf;
  5167. return B;
  5168. }
  5169. }
  5170. const tmpVec1$1 = new Vec3();
  5171. const tmpVec2$1 = new Vec3();
  5172. /**
  5173. * A Cone Twist constraint, useful for ragdolls.
  5174. */
  5175. class ConeTwistConstraint extends PointToPointConstraint {
  5176. /**
  5177. * The axis direction for the constraint of the body A.
  5178. */
  5179. /**
  5180. * The axis direction for the constraint of the body B.
  5181. */
  5182. /**
  5183. * The aperture angle of the cone.
  5184. */
  5185. /**
  5186. * The twist angle of the joint.
  5187. */
  5188. constructor(bodyA, bodyB, options = {}) {
  5189. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between
  5190. const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  5191. const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  5192. super(bodyA, pivotA, bodyB, pivotB, maxForce);
  5193. this.axisA = void 0;
  5194. this.axisB = void 0;
  5195. this.angle = void 0;
  5196. this.twistAngle = void 0;
  5197. this.coneEquation = void 0;
  5198. this.twistEquation = void 0;
  5199. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  5200. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  5201. this.collideConnected = !!options.collideConnected;
  5202. this.angle = typeof options.angle !== 'undefined' ? options.angle : 0;
  5203. const c = this.coneEquation = new ConeEquation(bodyA, bodyB, options);
  5204. const t = this.twistEquation = new RotationalEquation(bodyA, bodyB, options);
  5205. this.twistAngle = typeof options.twistAngle !== 'undefined' ? options.twistAngle : 0; // Make the cone equation push the bodies toward the cone axis, not outward
  5206. c.maxForce = 0;
  5207. c.minForce = -maxForce; // Make the twist equation add torque toward the initial position
  5208. t.maxForce = 0;
  5209. t.minForce = -maxForce;
  5210. this.equations.push(c, t);
  5211. }
  5212. update() {
  5213. const bodyA = this.bodyA;
  5214. const bodyB = this.bodyB;
  5215. const cone = this.coneEquation;
  5216. const twist = this.twistEquation;
  5217. super.update(); // Update the axes to the cone constraint
  5218. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  5219. bodyB.vectorToWorldFrame(this.axisB, cone.axisB); // Update the world axes in the twist constraint
  5220. this.axisA.tangents(twist.axisA, twist.axisA);
  5221. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  5222. this.axisB.tangents(twist.axisB, twist.axisB);
  5223. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  5224. cone.angle = this.angle;
  5225. twist.maxAngle = this.twistAngle;
  5226. }
  5227. }
  5228. /**
  5229. * Constrains two bodies to be at a constant distance from each others center of mass.
  5230. */
  5231. class DistanceConstraint extends Constraint {
  5232. /**
  5233. * The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  5234. */
  5235. /**
  5236. * @param distance The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB.
  5237. * @param maxForce The maximum force that should be applied to constrain the bodies.
  5238. */
  5239. constructor(bodyA, bodyB, distance, maxForce = 1e6) {
  5240. super(bodyA, bodyB);
  5241. this.distance = void 0;
  5242. this.distanceEquation = void 0;
  5243. if (typeof distance === 'undefined') {
  5244. distance = bodyA.position.distanceTo(bodyB.position);
  5245. }
  5246. this.distance = distance;
  5247. const eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  5248. this.equations.push(eq); // Make it bidirectional
  5249. eq.minForce = -maxForce;
  5250. eq.maxForce = maxForce;
  5251. }
  5252. /**
  5253. * update
  5254. */
  5255. update() {
  5256. const bodyA = this.bodyA;
  5257. const bodyB = this.bodyB;
  5258. const eq = this.distanceEquation;
  5259. const halfDist = this.distance * 0.5;
  5260. const normal = eq.ni;
  5261. bodyB.position.vsub(bodyA.position, normal);
  5262. normal.normalize();
  5263. normal.scale(halfDist, eq.ri);
  5264. normal.scale(-halfDist, eq.rj);
  5265. }
  5266. }
  5267. /**
  5268. * Lock constraint. Will remove all degrees of freedom between the bodies.
  5269. */
  5270. class LockConstraint extends PointToPointConstraint {
  5271. constructor(bodyA, bodyB, options = {}) {
  5272. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6; // Set pivot point in between
  5273. const pivotA = new Vec3();
  5274. const pivotB = new Vec3();
  5275. const halfWay = new Vec3();
  5276. bodyA.position.vadd(bodyB.position, halfWay);
  5277. halfWay.scale(0.5, halfWay);
  5278. bodyB.pointToLocalFrame(halfWay, pivotB);
  5279. bodyA.pointToLocalFrame(halfWay, pivotA); // The point-to-point constraint will keep a point shared between the bodies
  5280. super(bodyA, pivotA, bodyB, pivotB, maxForce); // Store initial rotation of the bodies as unit vectors in the local body spaces
  5281. this.xA = void 0;
  5282. this.xB = void 0;
  5283. this.yA = void 0;
  5284. this.yB = void 0;
  5285. this.zA = void 0;
  5286. this.zB = void 0;
  5287. this.rotationalEquation1 = void 0;
  5288. this.rotationalEquation2 = void 0;
  5289. this.rotationalEquation3 = void 0;
  5290. this.motorEquation = void 0;
  5291. this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);
  5292. this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);
  5293. this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);
  5294. this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);
  5295. this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);
  5296. this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z); // ...and the following rotational equations will keep all rotational DOF's in place
  5297. const r1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
  5298. const r2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
  5299. const r3 = this.rotationalEquation3 = new RotationalEquation(bodyA, bodyB, options);
  5300. this.equations.push(r1, r2, r3);
  5301. }
  5302. /**
  5303. * update
  5304. */
  5305. update() {
  5306. const bodyA = this.bodyA;
  5307. const bodyB = this.bodyB;
  5308. this.motorEquation;
  5309. const r1 = this.rotationalEquation1;
  5310. const r2 = this.rotationalEquation2;
  5311. const r3 = this.rotationalEquation3;
  5312. super.update(); // These vector pairs must be orthogonal
  5313. bodyA.vectorToWorldFrame(this.xA, r1.axisA);
  5314. bodyB.vectorToWorldFrame(this.yB, r1.axisB);
  5315. bodyA.vectorToWorldFrame(this.yA, r2.axisA);
  5316. bodyB.vectorToWorldFrame(this.zB, r2.axisB);
  5317. bodyA.vectorToWorldFrame(this.zA, r3.axisA);
  5318. bodyB.vectorToWorldFrame(this.xB, r3.axisB);
  5319. }
  5320. }
  5321. /**
  5322. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  5323. */
  5324. class RotationalMotorEquation extends Equation {
  5325. /**
  5326. * World oriented rotational axis.
  5327. */
  5328. /**
  5329. * World oriented rotational axis.
  5330. */
  5331. /**
  5332. * Motor velocity.
  5333. */
  5334. constructor(bodyA, bodyB, maxForce = 1e6) {
  5335. super(bodyA, bodyB, -maxForce, maxForce);
  5336. this.axisA = void 0;
  5337. this.axisB = void 0;
  5338. this.targetVelocity = void 0;
  5339. this.axisA = new Vec3();
  5340. this.axisB = new Vec3();
  5341. this.targetVelocity = 0;
  5342. }
  5343. computeB(h) {
  5344. this.a;
  5345. const b = this.b;
  5346. this.bi;
  5347. this.bj;
  5348. const axisA = this.axisA;
  5349. const axisB = this.axisB;
  5350. const GA = this.jacobianElementA;
  5351. const GB = this.jacobianElementB; // g = 0
  5352. // gdot = axisA * wi - axisB * wj
  5353. // gdot = G * W = G * [vi wi vj wj]
  5354. // =>
  5355. // G = [0 axisA 0 -axisB]
  5356. GA.rotational.copy(axisA);
  5357. axisB.negate(GB.rotational);
  5358. const GW = this.computeGW() - this.targetVelocity;
  5359. const GiMf = this.computeGiMf();
  5360. const B = -GW * b - h * GiMf;
  5361. return B;
  5362. }
  5363. }
  5364. /**
  5365. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  5366. */
  5367. class HingeConstraint extends PointToPointConstraint {
  5368. /**
  5369. * Rotation axis, defined locally in bodyA.
  5370. */
  5371. /**
  5372. * Rotation axis, defined locally in bodyB.
  5373. */
  5374. constructor(bodyA, bodyB, options = {}) {
  5375. const maxForce = typeof options.maxForce !== 'undefined' ? options.maxForce : 1e6;
  5376. const pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  5377. const pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  5378. super(bodyA, pivotA, bodyB, pivotB, maxForce);
  5379. this.axisA = void 0;
  5380. this.axisB = void 0;
  5381. this.rotationalEquation1 = void 0;
  5382. this.rotationalEquation2 = void 0;
  5383. this.motorEquation = void 0;
  5384. const axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  5385. axisA.normalize();
  5386. const axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1, 0, 0);
  5387. axisB.normalize();
  5388. this.collideConnected = !!options.collideConnected;
  5389. const rotational1 = this.rotationalEquation1 = new RotationalEquation(bodyA, bodyB, options);
  5390. const rotational2 = this.rotationalEquation2 = new RotationalEquation(bodyA, bodyB, options);
  5391. const motor = this.motorEquation = new RotationalMotorEquation(bodyA, bodyB, maxForce);
  5392. motor.enabled = false; // Not enabled by default
  5393. // Equations to be fed to the solver
  5394. this.equations.push(rotational1, rotational2, motor);
  5395. }
  5396. /**
  5397. * enableMotor
  5398. */
  5399. enableMotor() {
  5400. this.motorEquation.enabled = true;
  5401. }
  5402. /**
  5403. * disableMotor
  5404. */
  5405. disableMotor() {
  5406. this.motorEquation.enabled = false;
  5407. }
  5408. /**
  5409. * setMotorSpeed
  5410. */
  5411. setMotorSpeed(speed) {
  5412. this.motorEquation.targetVelocity = speed;
  5413. }
  5414. /**
  5415. * setMotorMaxForce
  5416. */
  5417. setMotorMaxForce(maxForce) {
  5418. this.motorEquation.maxForce = maxForce;
  5419. this.motorEquation.minForce = -maxForce;
  5420. }
  5421. /**
  5422. * update
  5423. */
  5424. update() {
  5425. const bodyA = this.bodyA;
  5426. const bodyB = this.bodyB;
  5427. const motor = this.motorEquation;
  5428. const r1 = this.rotationalEquation1;
  5429. const r2 = this.rotationalEquation2;
  5430. const worldAxisA = HingeConstraint_update_tmpVec1;
  5431. const worldAxisB = HingeConstraint_update_tmpVec2;
  5432. const axisA = this.axisA;
  5433. const axisB = this.axisB;
  5434. super.update(); // Get world axes
  5435. bodyA.quaternion.vmult(axisA, worldAxisA);
  5436. bodyB.quaternion.vmult(axisB, worldAxisB);
  5437. worldAxisA.tangents(r1.axisA, r2.axisA);
  5438. r1.axisB.copy(worldAxisB);
  5439. r2.axisB.copy(worldAxisB);
  5440. if (this.motorEquation.enabled) {
  5441. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  5442. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  5443. }
  5444. }
  5445. }
  5446. const HingeConstraint_update_tmpVec1 = new Vec3();
  5447. const HingeConstraint_update_tmpVec2 = new Vec3();
  5448. /**
  5449. * Constrains the slipping in a contact along a tangent
  5450. */
  5451. class FrictionEquation extends Equation {
  5452. // Tangent
  5453. /**
  5454. * @param slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  5455. */
  5456. constructor(bodyA, bodyB, slipForce) {
  5457. super(bodyA, bodyB, -slipForce, slipForce);
  5458. this.ri = void 0;
  5459. this.rj = void 0;
  5460. this.t = void 0;
  5461. this.ri = new Vec3();
  5462. this.rj = new Vec3();
  5463. this.t = new Vec3();
  5464. }
  5465. computeB(h) {
  5466. this.a;
  5467. const b = this.b;
  5468. this.bi;
  5469. this.bj;
  5470. const ri = this.ri;
  5471. const rj = this.rj;
  5472. const rixt = FrictionEquation_computeB_temp1;
  5473. const rjxt = FrictionEquation_computeB_temp2;
  5474. const t = this.t; // Caluclate cross products
  5475. ri.cross(t, rixt);
  5476. rj.cross(t, rjxt); // G = [-t -rixt t rjxt]
  5477. // And remember, this is a pure velocity constraint, g is always zero!
  5478. const GA = this.jacobianElementA;
  5479. const GB = this.jacobianElementB;
  5480. t.negate(GA.spatial);
  5481. rixt.negate(GA.rotational);
  5482. GB.spatial.copy(t);
  5483. GB.rotational.copy(rjxt);
  5484. const GW = this.computeGW();
  5485. const GiMf = this.computeGiMf();
  5486. const B = -GW * b - h * GiMf;
  5487. return B;
  5488. }
  5489. }
  5490. const FrictionEquation_computeB_temp1 = new Vec3();
  5491. const FrictionEquation_computeB_temp2 = new Vec3();
  5492. /**
  5493. * Defines what happens when two materials meet.
  5494. * @todo Refactor materials to materialA and materialB
  5495. */
  5496. class ContactMaterial {
  5497. /**
  5498. * Identifier of this material.
  5499. */
  5500. /**
  5501. * Participating materials.
  5502. */
  5503. /**
  5504. * Friction coefficient.
  5505. * @default 0.3
  5506. */
  5507. /**
  5508. * Restitution coefficient.
  5509. * @default 0.3
  5510. */
  5511. /**
  5512. * Stiffness of the produced contact equations.
  5513. * @default 1e7
  5514. */
  5515. /**
  5516. * Relaxation time of the produced contact equations.
  5517. * @default 3
  5518. */
  5519. /**
  5520. * Stiffness of the produced friction equations.
  5521. * @default 1e7
  5522. */
  5523. /**
  5524. * Relaxation time of the produced friction equations
  5525. * @default 3
  5526. */
  5527. constructor(m1, m2, options) {
  5528. this.id = void 0;
  5529. this.materials = void 0;
  5530. this.friction = void 0;
  5531. this.restitution = void 0;
  5532. this.contactEquationStiffness = void 0;
  5533. this.contactEquationRelaxation = void 0;
  5534. this.frictionEquationStiffness = void 0;
  5535. this.frictionEquationRelaxation = void 0;
  5536. options = Utils.defaults(options, {
  5537. friction: 0.3,
  5538. restitution: 0.3,
  5539. contactEquationStiffness: 1e7,
  5540. contactEquationRelaxation: 3,
  5541. frictionEquationStiffness: 1e7,
  5542. frictionEquationRelaxation: 3
  5543. });
  5544. this.id = ContactMaterial.idCounter++;
  5545. this.materials = [m1, m2];
  5546. this.friction = options.friction;
  5547. this.restitution = options.restitution;
  5548. this.contactEquationStiffness = options.contactEquationStiffness;
  5549. this.contactEquationRelaxation = options.contactEquationRelaxation;
  5550. this.frictionEquationStiffness = options.frictionEquationStiffness;
  5551. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  5552. }
  5553. }
  5554. ContactMaterial.idCounter = 0;
  5555. /**
  5556. * Defines a physics material.
  5557. */
  5558. class Material {
  5559. /**
  5560. * Material name.
  5561. * If options is a string, name will be set to that string.
  5562. * @todo Deprecate this
  5563. */
  5564. /** Material id. */
  5565. /**
  5566. * Friction for this material.
  5567. * If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.
  5568. */
  5569. /**
  5570. * Restitution for this material.
  5571. * If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from `defaultContactMaterial` in the World will be used.
  5572. */
  5573. constructor(options = {}) {
  5574. this.name = void 0;
  5575. this.id = void 0;
  5576. this.friction = void 0;
  5577. this.restitution = void 0;
  5578. let name = ''; // Backwards compatibility fix
  5579. if (typeof options === 'string') {
  5580. //console.warn(`Passing a string to MaterialOptions is deprecated, and has no effect`)
  5581. name = options;
  5582. options = {};
  5583. }
  5584. this.name = name;
  5585. this.id = Material.idCounter++;
  5586. this.friction = typeof options.friction !== 'undefined' ? options.friction : -1;
  5587. this.restitution = typeof options.restitution !== 'undefined' ? options.restitution : -1;
  5588. }
  5589. }
  5590. Material.idCounter = 0;
  5591. /**
  5592. * A spring, connecting two bodies.
  5593. * @example
  5594. * const spring = new Spring(boxBody, sphereBody, {
  5595. * restLength: 0,
  5596. * stiffness: 50,
  5597. * damping: 1,
  5598. * })
  5599. *
  5600. * // Compute the force after each step
  5601. * world.addEventListener('postStep', (event) => {
  5602. * spring.applyForce()
  5603. * })
  5604. */
  5605. class Spring {
  5606. /**
  5607. * Rest length of the spring. A number > 0.
  5608. * @default 1
  5609. */
  5610. /**
  5611. * Stiffness of the spring. A number >= 0.
  5612. * @default 100
  5613. */
  5614. /**
  5615. * Damping of the spring. A number >= 0.
  5616. * @default 1
  5617. */
  5618. /**
  5619. * First connected body.
  5620. */
  5621. /**
  5622. * Second connected body.
  5623. */
  5624. /**
  5625. * Anchor for bodyA in local bodyA coordinates.
  5626. * Where to hook the spring to body A, in local body coordinates.
  5627. * @default new Vec3()
  5628. */
  5629. /**
  5630. * Anchor for bodyB in local bodyB coordinates.
  5631. * Where to hook the spring to body B, in local body coordinates.
  5632. * @default new Vec3()
  5633. */
  5634. constructor(bodyA, bodyB, options = {}) {
  5635. this.restLength = void 0;
  5636. this.stiffness = void 0;
  5637. this.damping = void 0;
  5638. this.bodyA = void 0;
  5639. this.bodyB = void 0;
  5640. this.localAnchorA = void 0;
  5641. this.localAnchorB = void 0;
  5642. this.restLength = typeof options.restLength === 'number' ? options.restLength : 1;
  5643. this.stiffness = options.stiffness || 100;
  5644. this.damping = options.damping || 1;
  5645. this.bodyA = bodyA;
  5646. this.bodyB = bodyB;
  5647. this.localAnchorA = new Vec3();
  5648. this.localAnchorB = new Vec3();
  5649. if (options.localAnchorA) {
  5650. this.localAnchorA.copy(options.localAnchorA);
  5651. }
  5652. if (options.localAnchorB) {
  5653. this.localAnchorB.copy(options.localAnchorB);
  5654. }
  5655. if (options.worldAnchorA) {
  5656. this.setWorldAnchorA(options.worldAnchorA);
  5657. }
  5658. if (options.worldAnchorB) {
  5659. this.setWorldAnchorB(options.worldAnchorB);
  5660. }
  5661. }
  5662. /**
  5663. * Set the anchor point on body A, using world coordinates.
  5664. */
  5665. setWorldAnchorA(worldAnchorA) {
  5666. this.bodyA.pointToLocalFrame(worldAnchorA, this.localAnchorA);
  5667. }
  5668. /**
  5669. * Set the anchor point on body B, using world coordinates.
  5670. */
  5671. setWorldAnchorB(worldAnchorB) {
  5672. this.bodyB.pointToLocalFrame(worldAnchorB, this.localAnchorB);
  5673. }
  5674. /**
  5675. * Get the anchor point on body A, in world coordinates.
  5676. * @param result The vector to store the result in.
  5677. */
  5678. getWorldAnchorA(result) {
  5679. this.bodyA.pointToWorldFrame(this.localAnchorA, result);
  5680. }
  5681. /**
  5682. * Get the anchor point on body B, in world coordinates.
  5683. * @param result The vector to store the result in.
  5684. */
  5685. getWorldAnchorB(result) {
  5686. this.bodyB.pointToWorldFrame(this.localAnchorB, result);
  5687. }
  5688. /**
  5689. * Apply the spring force to the connected bodies.
  5690. */
  5691. applyForce() {
  5692. const k = this.stiffness;
  5693. const d = this.damping;
  5694. const l = this.restLength;
  5695. const bodyA = this.bodyA;
  5696. const bodyB = this.bodyB;
  5697. const r = applyForce_r;
  5698. const r_unit = applyForce_r_unit;
  5699. const u = applyForce_u;
  5700. const f = applyForce_f;
  5701. const tmp = applyForce_tmp;
  5702. const worldAnchorA = applyForce_worldAnchorA;
  5703. const worldAnchorB = applyForce_worldAnchorB;
  5704. const ri = applyForce_ri;
  5705. const rj = applyForce_rj;
  5706. const ri_x_f = applyForce_ri_x_f;
  5707. const rj_x_f = applyForce_rj_x_f; // Get world anchors
  5708. this.getWorldAnchorA(worldAnchorA);
  5709. this.getWorldAnchorB(worldAnchorB); // Get offset points
  5710. worldAnchorA.vsub(bodyA.position, ri);
  5711. worldAnchorB.vsub(bodyB.position, rj); // Compute distance vector between world anchor points
  5712. worldAnchorB.vsub(worldAnchorA, r);
  5713. const rlen = r.length();
  5714. r_unit.copy(r);
  5715. r_unit.normalize(); // Compute relative velocity of the anchor points, u
  5716. bodyB.velocity.vsub(bodyA.velocity, u); // Add rotational velocity
  5717. bodyB.angularVelocity.cross(rj, tmp);
  5718. u.vadd(tmp, u);
  5719. bodyA.angularVelocity.cross(ri, tmp);
  5720. u.vsub(tmp, u); // F = - k * ( x - L ) - D * ( u )
  5721. r_unit.scale(-k * (rlen - l) - d * u.dot(r_unit), f); // Add forces to bodies
  5722. bodyA.force.vsub(f, bodyA.force);
  5723. bodyB.force.vadd(f, bodyB.force); // Angular force
  5724. ri.cross(f, ri_x_f);
  5725. rj.cross(f, rj_x_f);
  5726. bodyA.torque.vsub(ri_x_f, bodyA.torque);
  5727. bodyB.torque.vadd(rj_x_f, bodyB.torque);
  5728. }
  5729. }
  5730. const applyForce_r = new Vec3();
  5731. const applyForce_r_unit = new Vec3();
  5732. const applyForce_u = new Vec3();
  5733. const applyForce_f = new Vec3();
  5734. const applyForce_worldAnchorA = new Vec3();
  5735. const applyForce_worldAnchorB = new Vec3();
  5736. const applyForce_ri = new Vec3();
  5737. const applyForce_rj = new Vec3();
  5738. const applyForce_ri_x_f = new Vec3();
  5739. const applyForce_rj_x_f = new Vec3();
  5740. const applyForce_tmp = new Vec3();
  5741. /**
  5742. * WheelInfo
  5743. */
  5744. class WheelInfo {
  5745. /**
  5746. * Max travel distance of the suspension, in meters.
  5747. * @default 1
  5748. */
  5749. /**
  5750. * Speed to apply to the wheel rotation when the wheel is sliding.
  5751. * @default -0.1
  5752. */
  5753. /**
  5754. * If the customSlidingRotationalSpeed should be used.
  5755. * @default false
  5756. */
  5757. /**
  5758. * sliding
  5759. */
  5760. /**
  5761. * Connection point, defined locally in the chassis body frame.
  5762. */
  5763. /**
  5764. * chassisConnectionPointWorld
  5765. */
  5766. /**
  5767. * directionLocal
  5768. */
  5769. /**
  5770. * directionWorld
  5771. */
  5772. /**
  5773. * axleLocal
  5774. */
  5775. /**
  5776. * axleWorld
  5777. */
  5778. /**
  5779. * suspensionRestLength
  5780. * @default 1
  5781. */
  5782. /**
  5783. * suspensionMaxLength
  5784. * @default 2
  5785. */
  5786. /**
  5787. * radius
  5788. * @default 1
  5789. */
  5790. /**
  5791. * suspensionStiffness
  5792. * @default 100
  5793. */
  5794. /**
  5795. * dampingCompression
  5796. * @default 10
  5797. */
  5798. /**
  5799. * dampingRelaxation
  5800. * @default 10
  5801. */
  5802. /**
  5803. * frictionSlip
  5804. * @default 10.5
  5805. */
  5806. /** forwardAcceleration */
  5807. /** sideAcceleration */
  5808. /**
  5809. * steering
  5810. * @default 0
  5811. */
  5812. /**
  5813. * Rotation value, in radians.
  5814. * @default 0
  5815. */
  5816. /**
  5817. * deltaRotation
  5818. * @default 0
  5819. */
  5820. /**
  5821. * rollInfluence
  5822. * @default 0.01
  5823. */
  5824. /**
  5825. * maxSuspensionForce
  5826. */
  5827. /**
  5828. * engineForce
  5829. */
  5830. /**
  5831. * brake
  5832. */
  5833. /**
  5834. * isFrontWheel
  5835. * @default true
  5836. */
  5837. /**
  5838. * clippedInvContactDotSuspension
  5839. * @default 1
  5840. */
  5841. /**
  5842. * suspensionRelativeVelocity
  5843. * @default 0
  5844. */
  5845. /**
  5846. * suspensionForce
  5847. * @default 0
  5848. */
  5849. /**
  5850. * slipInfo
  5851. */
  5852. /**
  5853. * skidInfo
  5854. * @default 0
  5855. */
  5856. /**
  5857. * suspensionLength
  5858. * @default 0
  5859. */
  5860. /**
  5861. * sideImpulse
  5862. */
  5863. /**
  5864. * forwardImpulse
  5865. */
  5866. /**
  5867. * The result from raycasting.
  5868. */
  5869. /**
  5870. * Wheel world transform.
  5871. */
  5872. /**
  5873. * isInContact
  5874. */
  5875. constructor(options = {}) {
  5876. this.maxSuspensionTravel = void 0;
  5877. this.customSlidingRotationalSpeed = void 0;
  5878. this.useCustomSlidingRotationalSpeed = void 0;
  5879. this.sliding = void 0;
  5880. this.chassisConnectionPointLocal = void 0;
  5881. this.chassisConnectionPointWorld = void 0;
  5882. this.directionLocal = void 0;
  5883. this.directionWorld = void 0;
  5884. this.axleLocal = void 0;
  5885. this.axleWorld = void 0;
  5886. this.suspensionRestLength = void 0;
  5887. this.suspensionMaxLength = void 0;
  5888. this.radius = void 0;
  5889. this.suspensionStiffness = void 0;
  5890. this.dampingCompression = void 0;
  5891. this.dampingRelaxation = void 0;
  5892. this.frictionSlip = void 0;
  5893. this.forwardAcceleration = void 0;
  5894. this.sideAcceleration = void 0;
  5895. this.steering = void 0;
  5896. this.rotation = void 0;
  5897. this.deltaRotation = void 0;
  5898. this.rollInfluence = void 0;
  5899. this.maxSuspensionForce = void 0;
  5900. this.engineForce = void 0;
  5901. this.brake = void 0;
  5902. this.isFrontWheel = void 0;
  5903. this.clippedInvContactDotSuspension = void 0;
  5904. this.suspensionRelativeVelocity = void 0;
  5905. this.suspensionForce = void 0;
  5906. this.slipInfo = void 0;
  5907. this.skidInfo = void 0;
  5908. this.suspensionLength = void 0;
  5909. this.sideImpulse = void 0;
  5910. this.forwardImpulse = void 0;
  5911. this.raycastResult = void 0;
  5912. this.worldTransform = void 0;
  5913. this.isInContact = void 0;
  5914. options = Utils.defaults(options, {
  5915. chassisConnectionPointLocal: new Vec3(),
  5916. chassisConnectionPointWorld: new Vec3(),
  5917. directionLocal: new Vec3(),
  5918. directionWorld: new Vec3(),
  5919. axleLocal: new Vec3(),
  5920. axleWorld: new Vec3(),
  5921. suspensionRestLength: 1,
  5922. suspensionMaxLength: 2,
  5923. radius: 1,
  5924. suspensionStiffness: 100,
  5925. dampingCompression: 10,
  5926. dampingRelaxation: 10,
  5927. frictionSlip: 10.5,
  5928. forwardAcceleration: 1,
  5929. sideAcceleration: 1,
  5930. steering: 0,
  5931. rotation: 0,
  5932. deltaRotation: 0,
  5933. rollInfluence: 0.01,
  5934. maxSuspensionForce: Number.MAX_VALUE,
  5935. isFrontWheel: true,
  5936. clippedInvContactDotSuspension: 1,
  5937. suspensionRelativeVelocity: 0,
  5938. suspensionForce: 0,
  5939. slipInfo: 0,
  5940. skidInfo: 0,
  5941. suspensionLength: 0,
  5942. maxSuspensionTravel: 1,
  5943. useCustomSlidingRotationalSpeed: false,
  5944. customSlidingRotationalSpeed: -0.1
  5945. });
  5946. this.maxSuspensionTravel = options.maxSuspensionTravel;
  5947. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  5948. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  5949. this.sliding = false;
  5950. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  5951. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  5952. this.directionLocal = options.directionLocal.clone();
  5953. this.directionWorld = options.directionWorld.clone();
  5954. this.axleLocal = options.axleLocal.clone();
  5955. this.axleWorld = options.axleWorld.clone();
  5956. this.suspensionRestLength = options.suspensionRestLength;
  5957. this.suspensionMaxLength = options.suspensionMaxLength;
  5958. this.radius = options.radius;
  5959. this.suspensionStiffness = options.suspensionStiffness;
  5960. this.dampingCompression = options.dampingCompression;
  5961. this.dampingRelaxation = options.dampingRelaxation;
  5962. this.frictionSlip = options.frictionSlip;
  5963. this.forwardAcceleration = options.forwardAcceleration;
  5964. this.sideAcceleration = options.sideAcceleration;
  5965. this.steering = 0;
  5966. this.rotation = 0;
  5967. this.deltaRotation = 0;
  5968. this.rollInfluence = options.rollInfluence;
  5969. this.maxSuspensionForce = options.maxSuspensionForce;
  5970. this.engineForce = 0;
  5971. this.brake = 0;
  5972. this.isFrontWheel = options.isFrontWheel;
  5973. this.clippedInvContactDotSuspension = 1;
  5974. this.suspensionRelativeVelocity = 0;
  5975. this.suspensionForce = 0;
  5976. this.slipInfo = 0;
  5977. this.skidInfo = 0;
  5978. this.suspensionLength = 0;
  5979. this.sideImpulse = 0;
  5980. this.forwardImpulse = 0;
  5981. this.raycastResult = new RaycastResult();
  5982. this.worldTransform = new Transform();
  5983. this.isInContact = false;
  5984. }
  5985. updateWheel(chassis) {
  5986. const raycastResult = this.raycastResult;
  5987. if (this.isInContact) {
  5988. const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  5989. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  5990. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  5991. const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);
  5992. if (project >= -0.1) {
  5993. this.suspensionRelativeVelocity = 0.0;
  5994. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  5995. } else {
  5996. const inv = -1 / project;
  5997. this.suspensionRelativeVelocity = projVel * inv;
  5998. this.clippedInvContactDotSuspension = inv;
  5999. }
  6000. } else {
  6001. // Not in contact : position wheel in a nice (rest length) position
  6002. raycastResult.suspensionLength = this.suspensionRestLength;
  6003. this.suspensionRelativeVelocity = 0.0;
  6004. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  6005. this.clippedInvContactDotSuspension = 1.0;
  6006. }
  6007. }
  6008. }
  6009. const chassis_velocity_at_contactPoint = new Vec3();
  6010. const relpos = new Vec3();
  6011. /**
  6012. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  6013. */
  6014. class RaycastVehicle {
  6015. /** The car chassis body. */
  6016. /** The wheels. */
  6017. /** Will be set to true if the car is sliding. */
  6018. /** Index of the right axis. x=0, y=1, z=2 */
  6019. /** Index of the forward axis. x=0, y=1, z=2 */
  6020. /** Index of the up axis. x=0, y=1, z=2 */
  6021. /** The constraints. */
  6022. /** Optional pre-step callback. */
  6023. /** Number of wheels on the ground. */
  6024. constructor(options) {
  6025. this.chassisBody = void 0;
  6026. this.wheelInfos = void 0;
  6027. this.sliding = void 0;
  6028. this.world = void 0;
  6029. this.indexRightAxis = void 0;
  6030. this.indexForwardAxis = void 0;
  6031. this.indexUpAxis = void 0;
  6032. this.constraints = void 0;
  6033. this.preStepCallback = void 0;
  6034. this.currentVehicleSpeedKmHour = void 0;
  6035. this.numWheelsOnGround = void 0;
  6036. this.chassisBody = options.chassisBody;
  6037. this.wheelInfos = [];
  6038. this.sliding = false;
  6039. this.world = null;
  6040. this.indexRightAxis = typeof options.indexRightAxis !== 'undefined' ? options.indexRightAxis : 2;
  6041. this.indexForwardAxis = typeof options.indexForwardAxis !== 'undefined' ? options.indexForwardAxis : 0;
  6042. this.indexUpAxis = typeof options.indexUpAxis !== 'undefined' ? options.indexUpAxis : 1;
  6043. this.constraints = [];
  6044. this.preStepCallback = () => {};
  6045. this.currentVehicleSpeedKmHour = 0;
  6046. this.numWheelsOnGround = 0;
  6047. }
  6048. /**
  6049. * Add a wheel. For information about the options, see `WheelInfo`.
  6050. */
  6051. addWheel(options = {}) {
  6052. const info = new WheelInfo(options);
  6053. const index = this.wheelInfos.length;
  6054. this.wheelInfos.push(info);
  6055. return index;
  6056. }
  6057. /**
  6058. * Set the steering value of a wheel.
  6059. */
  6060. setSteeringValue(value, wheelIndex) {
  6061. const wheel = this.wheelInfos[wheelIndex];
  6062. wheel.steering = value;
  6063. }
  6064. /**
  6065. * Set the wheel force to apply on one of the wheels each time step
  6066. */
  6067. applyEngineForce(value, wheelIndex) {
  6068. this.wheelInfos[wheelIndex].engineForce = value;
  6069. }
  6070. /**
  6071. * Set the braking force of a wheel
  6072. */
  6073. setBrake(brake, wheelIndex) {
  6074. this.wheelInfos[wheelIndex].brake = brake;
  6075. }
  6076. /**
  6077. * Add the vehicle including its constraints to the world.
  6078. */
  6079. addToWorld(world) {
  6080. world.addBody(this.chassisBody);
  6081. const that = this;
  6082. this.preStepCallback = () => {
  6083. that.updateVehicle(world.dt);
  6084. };
  6085. world.addEventListener('preStep', this.preStepCallback);
  6086. this.world = world;
  6087. }
  6088. /**
  6089. * Get one of the wheel axles, world-oriented.
  6090. */
  6091. getVehicleAxisWorld(axisIndex, result) {
  6092. result.set(axisIndex === 0 ? 1 : 0, axisIndex === 1 ? 1 : 0, axisIndex === 2 ? 1 : 0);
  6093. this.chassisBody.vectorToWorldFrame(result, result);
  6094. }
  6095. updateVehicle(timeStep) {
  6096. const wheelInfos = this.wheelInfos;
  6097. const numWheels = wheelInfos.length;
  6098. const chassisBody = this.chassisBody;
  6099. for (let i = 0; i < numWheels; i++) {
  6100. this.updateWheelTransform(i);
  6101. }
  6102. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();
  6103. const forwardWorld = new Vec3();
  6104. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  6105. if (forwardWorld.dot(chassisBody.velocity) < 0) {
  6106. this.currentVehicleSpeedKmHour *= -1;
  6107. } // simulate suspension
  6108. for (let i = 0; i < numWheels; i++) {
  6109. this.castRay(wheelInfos[i]);
  6110. }
  6111. this.updateSuspension(timeStep);
  6112. const impulse = new Vec3();
  6113. const relpos = new Vec3();
  6114. for (let i = 0; i < numWheels; i++) {
  6115. //apply suspension force
  6116. const wheel = wheelInfos[i];
  6117. let suspensionForce = wheel.suspensionForce;
  6118. if (suspensionForce > wheel.maxSuspensionForce) {
  6119. suspensionForce = wheel.maxSuspensionForce;
  6120. }
  6121. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  6122. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  6123. chassisBody.applyImpulse(impulse, relpos);
  6124. }
  6125. this.updateFriction(timeStep);
  6126. const hitNormalWorldScaledWithProj = new Vec3();
  6127. const fwd = new Vec3();
  6128. const vel = new Vec3();
  6129. for (let i = 0; i < numWheels; i++) {
  6130. const wheel = wheelInfos[i]; //const relpos = new Vec3();
  6131. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  6132. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel); // Hack to get the rotation in the correct direction
  6133. let m = 1;
  6134. switch (this.indexUpAxis) {
  6135. case 1:
  6136. m = -1;
  6137. break;
  6138. }
  6139. if (wheel.isInContact) {
  6140. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  6141. const proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  6142. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  6143. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  6144. const proj2 = fwd.dot(vel);
  6145. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  6146. }
  6147. if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed) {
  6148. // Apply custom rotation when accelerating and sliding
  6149. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  6150. } // Lock wheels
  6151. if (Math.abs(wheel.brake) > Math.abs(wheel.engineForce)) {
  6152. wheel.deltaRotation = 0;
  6153. }
  6154. wheel.rotation += wheel.deltaRotation; // Use the old value
  6155. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  6156. }
  6157. }
  6158. updateSuspension(deltaTime) {
  6159. const chassisBody = this.chassisBody;
  6160. const chassisMass = chassisBody.mass;
  6161. const wheelInfos = this.wheelInfos;
  6162. const numWheels = wheelInfos.length;
  6163. for (let w_it = 0; w_it < numWheels; w_it++) {
  6164. const wheel = wheelInfos[w_it];
  6165. if (wheel.isInContact) {
  6166. let force; // Spring
  6167. const susp_length = wheel.suspensionRestLength;
  6168. const current_length = wheel.suspensionLength;
  6169. const length_diff = susp_length - current_length;
  6170. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension; // Damper
  6171. const projected_rel_vel = wheel.suspensionRelativeVelocity;
  6172. let susp_damping;
  6173. if (projected_rel_vel < 0) {
  6174. susp_damping = wheel.dampingCompression;
  6175. } else {
  6176. susp_damping = wheel.dampingRelaxation;
  6177. }
  6178. force -= susp_damping * projected_rel_vel;
  6179. wheel.suspensionForce = force * chassisMass;
  6180. if (wheel.suspensionForce < 0) {
  6181. wheel.suspensionForce = 0;
  6182. }
  6183. } else {
  6184. wheel.suspensionForce = 0;
  6185. }
  6186. }
  6187. }
  6188. /**
  6189. * Remove the vehicle including its constraints from the world.
  6190. */
  6191. removeFromWorld(world) {
  6192. this.constraints;
  6193. world.removeBody(this.chassisBody);
  6194. world.removeEventListener('preStep', this.preStepCallback);
  6195. this.world = null;
  6196. }
  6197. castRay(wheel) {
  6198. const rayvector = castRay_rayvector;
  6199. const target = castRay_target;
  6200. this.updateWheelTransformWorld(wheel);
  6201. const chassisBody = this.chassisBody;
  6202. let depth = -1;
  6203. const raylen = wheel.suspensionRestLength + wheel.radius;
  6204. wheel.directionWorld.scale(raylen, rayvector);
  6205. const source = wheel.chassisConnectionPointWorld;
  6206. source.vadd(rayvector, target);
  6207. const raycastResult = wheel.raycastResult;
  6208. raycastResult.reset(); // Turn off ray collision with the chassis temporarily
  6209. const oldState = chassisBody.collisionResponse;
  6210. chassisBody.collisionResponse = false; // Cast ray against world
  6211. this.world.rayTest(source, target, raycastResult);
  6212. chassisBody.collisionResponse = oldState;
  6213. const object = raycastResult.body;
  6214. wheel.raycastResult.groundObject = 0;
  6215. if (object) {
  6216. depth = raycastResult.distance;
  6217. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  6218. wheel.isInContact = true;
  6219. const hitDistance = raycastResult.distance;
  6220. wheel.suspensionLength = hitDistance - wheel.radius; // clamp on max suspension travel
  6221. const minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  6222. const maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  6223. if (wheel.suspensionLength < minSuspensionLength) {
  6224. wheel.suspensionLength = minSuspensionLength;
  6225. }
  6226. if (wheel.suspensionLength > maxSuspensionLength) {
  6227. wheel.suspensionLength = maxSuspensionLength;
  6228. wheel.raycastResult.reset();
  6229. }
  6230. const denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  6231. const chassis_velocity_at_contactPoint = new Vec3();
  6232. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  6233. const projVel = wheel.raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint);
  6234. if (denominator >= -0.1) {
  6235. wheel.suspensionRelativeVelocity = 0;
  6236. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  6237. } else {
  6238. const inv = -1 / denominator;
  6239. wheel.suspensionRelativeVelocity = projVel * inv;
  6240. wheel.clippedInvContactDotSuspension = inv;
  6241. }
  6242. } else {
  6243. //put wheel info as in rest position
  6244. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  6245. wheel.suspensionRelativeVelocity = 0.0;
  6246. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  6247. wheel.clippedInvContactDotSuspension = 1.0;
  6248. }
  6249. return depth;
  6250. }
  6251. updateWheelTransformWorld(wheel) {
  6252. wheel.isInContact = false;
  6253. const chassisBody = this.chassisBody;
  6254. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  6255. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  6256. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  6257. }
  6258. /**
  6259. * Update one of the wheel transform.
  6260. * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.
  6261. * @param wheelIndex The wheel index to update.
  6262. */
  6263. updateWheelTransform(wheelIndex) {
  6264. const up = tmpVec4;
  6265. const right = tmpVec5;
  6266. const fwd = tmpVec6;
  6267. const wheel = this.wheelInfos[wheelIndex];
  6268. this.updateWheelTransformWorld(wheel);
  6269. wheel.directionLocal.scale(-1, up);
  6270. right.copy(wheel.axleLocal);
  6271. up.cross(right, fwd);
  6272. fwd.normalize();
  6273. right.normalize(); // Rotate around steering over the wheelAxle
  6274. const steering = wheel.steering;
  6275. const steeringOrn = new Quaternion();
  6276. steeringOrn.setFromAxisAngle(up, steering);
  6277. const rotatingOrn = new Quaternion();
  6278. rotatingOrn.setFromAxisAngle(right, wheel.rotation); // World rotation of the wheel
  6279. const q = wheel.worldTransform.quaternion;
  6280. this.chassisBody.quaternion.mult(steeringOrn, q);
  6281. q.mult(rotatingOrn, q);
  6282. q.normalize(); // world position of the wheel
  6283. const p = wheel.worldTransform.position;
  6284. p.copy(wheel.directionWorld);
  6285. p.scale(wheel.suspensionLength, p);
  6286. p.vadd(wheel.chassisConnectionPointWorld, p);
  6287. }
  6288. /**
  6289. * Get the world transform of one of the wheels
  6290. */
  6291. getWheelTransformWorld(wheelIndex) {
  6292. return this.wheelInfos[wheelIndex].worldTransform;
  6293. }
  6294. updateFriction(timeStep) {
  6295. const surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj; //calculate the impulse, so that the wheels don't move sidewards
  6296. const wheelInfos = this.wheelInfos;
  6297. const numWheels = wheelInfos.length;
  6298. const chassisBody = this.chassisBody;
  6299. const forwardWS = updateFriction_forwardWS;
  6300. const axle = updateFriction_axle;
  6301. this.numWheelsOnGround = 0;
  6302. for (let i = 0; i < numWheels; i++) {
  6303. const wheel = wheelInfos[i];
  6304. const groundObject = wheel.raycastResult.body;
  6305. if (groundObject) {
  6306. this.numWheelsOnGround++;
  6307. }
  6308. wheel.sideImpulse = 0;
  6309. wheel.forwardImpulse = 0;
  6310. if (!forwardWS[i]) {
  6311. forwardWS[i] = new Vec3();
  6312. }
  6313. if (!axle[i]) {
  6314. axle[i] = new Vec3();
  6315. }
  6316. }
  6317. for (let i = 0; i < numWheels; i++) {
  6318. const wheel = wheelInfos[i];
  6319. const groundObject = wheel.raycastResult.body;
  6320. if (groundObject) {
  6321. const axlei = axle[i];
  6322. const wheelTrans = this.getWheelTransformWorld(i); // Get world axle
  6323. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  6324. const surfNormalWS = wheel.raycastResult.hitNormalWorld;
  6325. const proj = axlei.dot(surfNormalWS);
  6326. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  6327. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  6328. axlei.normalize();
  6329. surfNormalWS.cross(axlei, forwardWS[i]);
  6330. forwardWS[i].normalize();
  6331. wheel.sideImpulse = resolveSingleBilateral(chassisBody, wheel.raycastResult.hitPointWorld, groundObject, wheel.raycastResult.hitPointWorld, axlei);
  6332. wheel.sideImpulse *= sideFrictionStiffness2;
  6333. }
  6334. }
  6335. const sideFactor = 1;
  6336. const fwdFactor = 0.5;
  6337. this.sliding = false;
  6338. for (let i = 0; i < numWheels; i++) {
  6339. const wheel = wheelInfos[i];
  6340. const groundObject = wheel.raycastResult.body;
  6341. let rollingFriction = 0;
  6342. wheel.slipInfo = 1;
  6343. if (groundObject) {
  6344. const defaultRollingFrictionImpulse = 0;
  6345. const maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse; // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  6346. // rollingFriction = calcRollingFriction(contactPt);
  6347. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  6348. rollingFriction += wheel.engineForce * timeStep; // rollingFriction = 0;
  6349. const factor = maxImpulse / rollingFriction;
  6350. wheel.slipInfo *= factor;
  6351. } //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  6352. wheel.forwardImpulse = 0;
  6353. wheel.skidInfo = 1;
  6354. if (groundObject) {
  6355. wheel.skidInfo = 1;
  6356. const maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  6357. const maximpSide = maximp;
  6358. const maximpSquared = maximp * maximpSide;
  6359. wheel.forwardImpulse = rollingFriction; //wheelInfo.engineForce* timeStep;
  6360. const x = wheel.forwardImpulse * fwdFactor / wheel.forwardAcceleration;
  6361. const y = wheel.sideImpulse * sideFactor / wheel.sideAcceleration;
  6362. const impulseSquared = x * x + y * y;
  6363. wheel.sliding = false;
  6364. if (impulseSquared > maximpSquared) {
  6365. this.sliding = true;
  6366. wheel.sliding = true;
  6367. const factor = maximp / Math.sqrt(impulseSquared);
  6368. wheel.skidInfo *= factor;
  6369. }
  6370. }
  6371. }
  6372. if (this.sliding) {
  6373. for (let i = 0; i < numWheels; i++) {
  6374. const wheel = wheelInfos[i];
  6375. if (wheel.sideImpulse !== 0) {
  6376. if (wheel.skidInfo < 1) {
  6377. wheel.forwardImpulse *= wheel.skidInfo;
  6378. wheel.sideImpulse *= wheel.skidInfo;
  6379. }
  6380. }
  6381. }
  6382. } // apply the impulses
  6383. for (let i = 0; i < numWheels; i++) {
  6384. const wheel = wheelInfos[i];
  6385. const rel_pos = new Vec3();
  6386. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos); // cannons applyimpulse is using world coord for the position
  6387. //rel_pos.copy(wheel.raycastResult.hitPointWorld);
  6388. if (wheel.forwardImpulse !== 0) {
  6389. const impulse = new Vec3();
  6390. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  6391. chassisBody.applyImpulse(impulse, rel_pos);
  6392. }
  6393. if (wheel.sideImpulse !== 0) {
  6394. const groundObject = wheel.raycastResult.body;
  6395. const rel_pos2 = new Vec3();
  6396. wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2); //rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  6397. const sideImp = new Vec3();
  6398. axle[i].scale(wheel.sideImpulse, sideImp); // Scale the relative position in the up direction with rollInfluence.
  6399. // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).
  6400. chassisBody.vectorToLocalFrame(rel_pos, rel_pos);
  6401. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  6402. chassisBody.vectorToWorldFrame(rel_pos, rel_pos);
  6403. chassisBody.applyImpulse(sideImp, rel_pos); //apply friction impulse on the ground
  6404. sideImp.scale(-1, sideImp);
  6405. groundObject.applyImpulse(sideImp, rel_pos2);
  6406. }
  6407. }
  6408. }
  6409. }
  6410. const tmpVec4 = new Vec3();
  6411. const tmpVec5 = new Vec3();
  6412. const tmpVec6 = new Vec3();
  6413. new Ray();
  6414. const castRay_rayvector = new Vec3();
  6415. const castRay_target = new Vec3();
  6416. const directions = [new Vec3(1, 0, 0), new Vec3(0, 1, 0), new Vec3(0, 0, 1)];
  6417. const updateFriction_surfNormalWS_scaled_proj = new Vec3();
  6418. const updateFriction_axle = [];
  6419. const updateFriction_forwardWS = [];
  6420. const sideFrictionStiffness2 = 1;
  6421. const calcRollingFriction_vel1 = new Vec3();
  6422. const calcRollingFriction_vel2 = new Vec3();
  6423. const calcRollingFriction_vel = new Vec3();
  6424. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  6425. let j1 = 0;
  6426. const contactPosWorld = frictionPosWorld; // const rel_pos1 = new Vec3();
  6427. // const rel_pos2 = new Vec3();
  6428. const vel1 = calcRollingFriction_vel1;
  6429. const vel2 = calcRollingFriction_vel2;
  6430. const vel = calcRollingFriction_vel; // contactPosWorld.vsub(body0.position, rel_pos1);
  6431. // contactPosWorld.vsub(body1.position, rel_pos2);
  6432. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  6433. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  6434. vel1.vsub(vel2, vel);
  6435. const vrel = frictionDirectionWorld.dot(vel);
  6436. const denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  6437. const denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  6438. const relaxation = 1;
  6439. const jacDiagABInv = relaxation / (denom0 + denom1); // calculate j that moves us to zero relative velocity
  6440. j1 = -vrel * jacDiagABInv;
  6441. if (maxImpulse < j1) {
  6442. j1 = maxImpulse;
  6443. }
  6444. if (j1 < -maxImpulse) {
  6445. j1 = -maxImpulse;
  6446. }
  6447. return j1;
  6448. }
  6449. const computeImpulseDenominator_r0 = new Vec3();
  6450. const computeImpulseDenominator_c0 = new Vec3();
  6451. const computeImpulseDenominator_vec = new Vec3();
  6452. const computeImpulseDenominator_m = new Vec3();
  6453. function computeImpulseDenominator(body, pos, normal) {
  6454. const r0 = computeImpulseDenominator_r0;
  6455. const c0 = computeImpulseDenominator_c0;
  6456. const vec = computeImpulseDenominator_vec;
  6457. const m = computeImpulseDenominator_m;
  6458. pos.vsub(body.position, r0);
  6459. r0.cross(normal, c0);
  6460. body.invInertiaWorld.vmult(c0, m);
  6461. m.cross(r0, vec);
  6462. return body.invMass + normal.dot(vec);
  6463. }
  6464. const resolveSingleBilateral_vel1 = new Vec3();
  6465. const resolveSingleBilateral_vel2 = new Vec3();
  6466. const resolveSingleBilateral_vel = new Vec3(); // bilateral constraint between two dynamic objects
  6467. function resolveSingleBilateral(body1, pos1, body2, pos2, normal) {
  6468. const normalLenSqr = normal.lengthSquared();
  6469. if (normalLenSqr > 1.1) {
  6470. return 0; // no impulse
  6471. } // const rel_pos1 = new Vec3();
  6472. // const rel_pos2 = new Vec3();
  6473. // pos1.vsub(body1.position, rel_pos1);
  6474. // pos2.vsub(body2.position, rel_pos2);
  6475. const vel1 = resolveSingleBilateral_vel1;
  6476. const vel2 = resolveSingleBilateral_vel2;
  6477. const vel = resolveSingleBilateral_vel;
  6478. body1.getVelocityAtWorldPoint(pos1, vel1);
  6479. body2.getVelocityAtWorldPoint(pos2, vel2);
  6480. vel1.vsub(vel2, vel);
  6481. const rel_vel = normal.dot(vel);
  6482. const contactDamping = 0.2;
  6483. const massTerm = 1 / (body1.invMass + body2.invMass);
  6484. const impulse = -contactDamping * rel_vel * massTerm;
  6485. return impulse;
  6486. }
  6487. /**
  6488. * Spherical shape
  6489. * @example
  6490. * const radius = 1
  6491. * const sphereShape = new CANNON.Sphere(radius)
  6492. * const sphereBody = new CANNON.Body({ mass: 1, shape: sphereShape })
  6493. * world.addBody(sphereBody)
  6494. */
  6495. class Sphere extends Shape {
  6496. /**
  6497. * The radius of the sphere.
  6498. */
  6499. /**
  6500. *
  6501. * @param radius The radius of the sphere, a non-negative number.
  6502. */
  6503. constructor(radius) {
  6504. super({
  6505. type: Shape.types.SPHERE
  6506. });
  6507. this.radius = void 0;
  6508. this.radius = radius !== undefined ? radius : 1.0;
  6509. if (this.radius < 0) {
  6510. throw new Error('The sphere radius cannot be negative.');
  6511. }
  6512. this.updateBoundingSphereRadius();
  6513. }
  6514. /** calculateLocalInertia */
  6515. calculateLocalInertia(mass, target = new Vec3()) {
  6516. const I = 2.0 * mass * this.radius * this.radius / 5.0;
  6517. target.x = I;
  6518. target.y = I;
  6519. target.z = I;
  6520. return target;
  6521. }
  6522. /** volume */
  6523. volume() {
  6524. return 4.0 * Math.PI * Math.pow(this.radius, 3) / 3.0;
  6525. }
  6526. updateBoundingSphereRadius() {
  6527. this.boundingSphereRadius = this.radius;
  6528. }
  6529. calculateWorldAABB(pos, quat, min, max) {
  6530. const r = this.radius;
  6531. const axes = ['x', 'y', 'z'];
  6532. for (let i = 0; i < axes.length; i++) {
  6533. const ax = axes[i];
  6534. min[ax] = pos[ax] - r;
  6535. max[ax] = pos[ax] + r;
  6536. }
  6537. }
  6538. }
  6539. /**
  6540. * Simple vehicle helper class with spherical rigid body wheels.
  6541. */
  6542. class RigidVehicle {
  6543. /**
  6544. * The bodies of the wheels.
  6545. */
  6546. /**
  6547. * The chassis body.
  6548. */
  6549. /**
  6550. * The constraints.
  6551. */
  6552. /**
  6553. * The wheel axes.
  6554. */
  6555. /**
  6556. * The wheel forces.
  6557. */
  6558. constructor(options = {}) {
  6559. this.wheelBodies = void 0;
  6560. this.coordinateSystem = void 0;
  6561. this.chassisBody = void 0;
  6562. this.constraints = void 0;
  6563. this.wheelAxes = void 0;
  6564. this.wheelForces = void 0;
  6565. this.wheelBodies = [];
  6566. this.coordinateSystem = typeof options.coordinateSystem !== 'undefined' ? options.coordinateSystem.clone() : new Vec3(1, 2, 3);
  6567. if (options.chassisBody) {
  6568. this.chassisBody = options.chassisBody;
  6569. } else {
  6570. // No chassis body given. Create it!
  6571. this.chassisBody = new Body({
  6572. mass: 1,
  6573. shape: new Box(new Vec3(5, 0.5, 2))
  6574. });
  6575. }
  6576. this.constraints = [];
  6577. this.wheelAxes = [];
  6578. this.wheelForces = [];
  6579. }
  6580. /**
  6581. * Add a wheel
  6582. */
  6583. addWheel(options = {}) {
  6584. let wheelBody;
  6585. if (options.body) {
  6586. wheelBody = options.body;
  6587. } else {
  6588. // No wheel body given. Create it!
  6589. wheelBody = new Body({
  6590. mass: 1,
  6591. shape: new Sphere(1.2)
  6592. });
  6593. }
  6594. this.wheelBodies.push(wheelBody);
  6595. this.wheelForces.push(0); // Position constrain wheels
  6596. const position = typeof options.position !== 'undefined' ? options.position.clone() : new Vec3(); // Set position locally to the chassis
  6597. const worldPosition = new Vec3();
  6598. this.chassisBody.pointToWorldFrame(position, worldPosition);
  6599. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z); // Constrain wheel
  6600. const axis = typeof options.axis !== 'undefined' ? options.axis.clone() : new Vec3(0, 0, 1);
  6601. this.wheelAxes.push(axis);
  6602. const hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  6603. pivotA: position,
  6604. axisA: axis,
  6605. pivotB: Vec3.ZERO,
  6606. axisB: axis,
  6607. collideConnected: false
  6608. });
  6609. this.constraints.push(hingeConstraint);
  6610. return this.wheelBodies.length - 1;
  6611. }
  6612. /**
  6613. * Set the steering value of a wheel.
  6614. * @todo check coordinateSystem
  6615. */
  6616. setSteeringValue(value, wheelIndex) {
  6617. // Set angle of the hinge axis
  6618. const axis = this.wheelAxes[wheelIndex];
  6619. const c = Math.cos(value);
  6620. const s = Math.sin(value);
  6621. const x = axis.x;
  6622. const z = axis.z;
  6623. this.constraints[wheelIndex].axisA.set(-c * x + s * z, 0, s * x + c * z);
  6624. }
  6625. /**
  6626. * Set the target rotational speed of the hinge constraint.
  6627. */
  6628. setMotorSpeed(value, wheelIndex) {
  6629. const hingeConstraint = this.constraints[wheelIndex];
  6630. hingeConstraint.enableMotor();
  6631. hingeConstraint.motorTargetVelocity = value;
  6632. }
  6633. /**
  6634. * Set the target rotational speed of the hinge constraint.
  6635. */
  6636. disableMotor(wheelIndex) {
  6637. const hingeConstraint = this.constraints[wheelIndex];
  6638. hingeConstraint.disableMotor();
  6639. }
  6640. /**
  6641. * Set the wheel force to apply on one of the wheels each time step
  6642. */
  6643. setWheelForce(value, wheelIndex) {
  6644. this.wheelForces[wheelIndex] = value;
  6645. }
  6646. /**
  6647. * Apply a torque on one of the wheels.
  6648. */
  6649. applyWheelForce(value, wheelIndex) {
  6650. const axis = this.wheelAxes[wheelIndex];
  6651. const wheelBody = this.wheelBodies[wheelIndex];
  6652. const bodyTorque = wheelBody.torque;
  6653. axis.scale(value, torque);
  6654. wheelBody.vectorToWorldFrame(torque, torque);
  6655. bodyTorque.vadd(torque, bodyTorque);
  6656. }
  6657. /**
  6658. * Add the vehicle including its constraints to the world.
  6659. */
  6660. addToWorld(world) {
  6661. const constraints = this.constraints;
  6662. const bodies = this.wheelBodies.concat([this.chassisBody]);
  6663. for (let i = 0; i < bodies.length; i++) {
  6664. world.addBody(bodies[i]);
  6665. }
  6666. for (let i = 0; i < constraints.length; i++) {
  6667. world.addConstraint(constraints[i]);
  6668. }
  6669. world.addEventListener('preStep', this._update.bind(this));
  6670. }
  6671. _update() {
  6672. const wheelForces = this.wheelForces;
  6673. for (let i = 0; i < wheelForces.length; i++) {
  6674. this.applyWheelForce(wheelForces[i], i);
  6675. }
  6676. }
  6677. /**
  6678. * Remove the vehicle including its constraints from the world.
  6679. */
  6680. removeFromWorld(world) {
  6681. const constraints = this.constraints;
  6682. const bodies = this.wheelBodies.concat([this.chassisBody]);
  6683. for (let i = 0; i < bodies.length; i++) {
  6684. world.removeBody(bodies[i]);
  6685. }
  6686. for (let i = 0; i < constraints.length; i++) {
  6687. world.removeConstraint(constraints[i]);
  6688. }
  6689. }
  6690. /**
  6691. * Get current rotational velocity of a wheel
  6692. */
  6693. getWheelSpeed(wheelIndex) {
  6694. const axis = this.wheelAxes[wheelIndex];
  6695. const wheelBody = this.wheelBodies[wheelIndex];
  6696. const w = wheelBody.angularVelocity;
  6697. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  6698. return w.dot(worldAxis);
  6699. }
  6700. }
  6701. const torque = new Vec3();
  6702. const worldAxis = new Vec3();
  6703. /**
  6704. * Smoothed-particle hydrodynamics system
  6705. * @todo Make parameters customizable in the constructor
  6706. */
  6707. class SPHSystem {
  6708. /**
  6709. * The particles array.
  6710. */
  6711. /**
  6712. * Density of the system (kg/m3).
  6713. * @default 1
  6714. */
  6715. /**
  6716. * Distance below which two particles are considered to be neighbors.
  6717. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  6718. * @default 1
  6719. */
  6720. /**
  6721. * @default 1
  6722. */
  6723. /**
  6724. * Viscosity of the system.
  6725. * @default 0.01
  6726. */
  6727. /**
  6728. * @default 0.000001
  6729. */
  6730. constructor() {
  6731. this.particles = void 0;
  6732. this.density = void 0;
  6733. this.smoothingRadius = void 0;
  6734. this.speedOfSound = void 0;
  6735. this.viscosity = void 0;
  6736. this.eps = void 0;
  6737. this.pressures = void 0;
  6738. this.densities = void 0;
  6739. this.neighbors = void 0;
  6740. this.particles = [];
  6741. this.density = 1;
  6742. this.smoothingRadius = 1;
  6743. this.speedOfSound = 1;
  6744. this.viscosity = 0.01;
  6745. this.eps = 0.000001; // Stuff Computed per particle
  6746. this.pressures = [];
  6747. this.densities = [];
  6748. this.neighbors = [];
  6749. }
  6750. /**
  6751. * Add a particle to the system.
  6752. */
  6753. add(particle) {
  6754. this.particles.push(particle);
  6755. if (this.neighbors.length < this.particles.length) {
  6756. this.neighbors.push([]);
  6757. }
  6758. }
  6759. /**
  6760. * Remove a particle from the system.
  6761. */
  6762. remove(particle) {
  6763. const idx = this.particles.indexOf(particle);
  6764. if (idx !== -1) {
  6765. this.particles.splice(idx, 1);
  6766. if (this.neighbors.length > this.particles.length) {
  6767. this.neighbors.pop();
  6768. }
  6769. }
  6770. }
  6771. /**
  6772. * Get neighbors within smoothing volume, save in the array neighbors
  6773. */
  6774. getNeighbors(particle, neighbors) {
  6775. const N = this.particles.length;
  6776. const id = particle.id;
  6777. const R2 = this.smoothingRadius * this.smoothingRadius;
  6778. const dist = SPHSystem_getNeighbors_dist;
  6779. for (let i = 0; i !== N; i++) {
  6780. const p = this.particles[i];
  6781. p.position.vsub(particle.position, dist);
  6782. if (id !== p.id && dist.lengthSquared() < R2) {
  6783. neighbors.push(p);
  6784. }
  6785. }
  6786. }
  6787. update() {
  6788. const N = this.particles.length;
  6789. const dist = SPHSystem_update_dist;
  6790. const cs = this.speedOfSound;
  6791. const eps = this.eps;
  6792. for (let i = 0; i !== N; i++) {
  6793. const p = this.particles[i]; // Current particle
  6794. const neighbors = this.neighbors[i]; // Get neighbors
  6795. neighbors.length = 0;
  6796. this.getNeighbors(p, neighbors);
  6797. neighbors.push(this.particles[i]); // Add current too
  6798. const numNeighbors = neighbors.length; // Accumulate density for the particle
  6799. let sum = 0.0;
  6800. for (let j = 0; j !== numNeighbors; j++) {
  6801. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  6802. p.position.vsub(neighbors[j].position, dist);
  6803. const len = dist.length();
  6804. const weight = this.w(len);
  6805. sum += neighbors[j].mass * weight;
  6806. } // Save
  6807. this.densities[i] = sum;
  6808. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  6809. } // Add forces
  6810. // Sum to these accelerations
  6811. const a_pressure = SPHSystem_update_a_pressure;
  6812. const a_visc = SPHSystem_update_a_visc;
  6813. const gradW = SPHSystem_update_gradW;
  6814. const r_vec = SPHSystem_update_r_vec;
  6815. const u = SPHSystem_update_u;
  6816. for (let i = 0; i !== N; i++) {
  6817. const particle = this.particles[i];
  6818. a_pressure.set(0, 0, 0);
  6819. a_visc.set(0, 0, 0); // Init vars
  6820. let Pij;
  6821. let nabla;
  6822. const neighbors = this.neighbors[i];
  6823. const numNeighbors = neighbors.length; //printf("Neighbors: ");
  6824. for (let j = 0; j !== numNeighbors; j++) {
  6825. const neighbor = neighbors[j]; //printf("%d ",nj);
  6826. // Get r once for all..
  6827. particle.position.vsub(neighbor.position, r_vec);
  6828. const r = r_vec.length(); // Pressure contribution
  6829. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i] * this.densities[i] + eps) + this.pressures[j] / (this.densities[j] * this.densities[j] + eps));
  6830. this.gradw(r_vec, gradW); // Add to pressure acceleration
  6831. gradW.scale(Pij, gradW);
  6832. a_pressure.vadd(gradW, a_pressure); // Viscosity contribution
  6833. neighbor.velocity.vsub(particle.velocity, u);
  6834. u.scale(1.0 / (0.0001 + this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass, u);
  6835. nabla = this.nablaw(r);
  6836. u.scale(nabla, u); // Add to viscosity acceleration
  6837. a_visc.vadd(u, a_visc);
  6838. } // Calculate force
  6839. a_visc.scale(particle.mass, a_visc);
  6840. a_pressure.scale(particle.mass, a_pressure); // Add force to particles
  6841. particle.force.vadd(a_visc, particle.force);
  6842. particle.force.vadd(a_pressure, particle.force);
  6843. }
  6844. } // Calculate the weight using the W(r) weightfunction
  6845. w(r) {
  6846. // 315
  6847. const h = this.smoothingRadius;
  6848. return 315.0 / (64.0 * Math.PI * h ** 9) * (h * h - r * r) ** 3;
  6849. } // calculate gradient of the weight function
  6850. gradw(rVec, resultVec) {
  6851. const r = rVec.length();
  6852. const h = this.smoothingRadius;
  6853. rVec.scale(945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) ** 2, resultVec);
  6854. } // Calculate nabla(W)
  6855. nablaw(r) {
  6856. const h = this.smoothingRadius;
  6857. const nabla = 945.0 / (32.0 * Math.PI * h ** 9) * (h * h - r * r) * (7 * r * r - 3 * h * h);
  6858. return nabla;
  6859. }
  6860. }
  6861. const SPHSystem_getNeighbors_dist = new Vec3(); // Temp vectors for calculation
  6862. const SPHSystem_update_dist = new Vec3(); // Relative velocity
  6863. const SPHSystem_update_a_pressure = new Vec3();
  6864. const SPHSystem_update_a_visc = new Vec3();
  6865. const SPHSystem_update_gradW = new Vec3();
  6866. const SPHSystem_update_r_vec = new Vec3();
  6867. const SPHSystem_update_u = new Vec3();
  6868. /**
  6869. * Cylinder class.
  6870. * @example
  6871. * const radiusTop = 0.5
  6872. * const radiusBottom = 0.5
  6873. * const height = 2
  6874. * const numSegments = 12
  6875. * const cylinderShape = new CANNON.Cylinder(radiusTop, radiusBottom, height, numSegments)
  6876. * const cylinderBody = new CANNON.Body({ mass: 1, shape: cylinderShape })
  6877. * world.addBody(cylinderBody)
  6878. */
  6879. class Cylinder extends ConvexPolyhedron {
  6880. /** The radius of the top of the Cylinder. */
  6881. /** The radius of the bottom of the Cylinder. */
  6882. /** The height of the Cylinder. */
  6883. /** The number of segments to build the cylinder out of. */
  6884. /**
  6885. * @param radiusTop The radius of the top of the Cylinder.
  6886. * @param radiusBottom The radius of the bottom of the Cylinder.
  6887. * @param height The height of the Cylinder.
  6888. * @param numSegments The number of segments to build the cylinder out of.
  6889. */
  6890. constructor(radiusTop = 1, radiusBottom = 1, height = 1, numSegments = 8) {
  6891. if (radiusTop < 0) {
  6892. throw new Error('The cylinder radiusTop cannot be negative.');
  6893. }
  6894. if (radiusBottom < 0) {
  6895. throw new Error('The cylinder radiusBottom cannot be negative.');
  6896. }
  6897. const N = numSegments;
  6898. const vertices = [];
  6899. const axes = [];
  6900. const faces = [];
  6901. const bottomface = [];
  6902. const topface = [];
  6903. const cos = Math.cos;
  6904. const sin = Math.sin; // First bottom point
  6905. vertices.push(new Vec3(-radiusBottom * sin(0), -height * 0.5, radiusBottom * cos(0)));
  6906. bottomface.push(0); // First top point
  6907. vertices.push(new Vec3(-radiusTop * sin(0), height * 0.5, radiusTop * cos(0)));
  6908. topface.push(1);
  6909. for (let i = 0; i < N; i++) {
  6910. const theta = 2 * Math.PI / N * (i + 1);
  6911. const thetaN = 2 * Math.PI / N * (i + 0.5);
  6912. if (i < N - 1) {
  6913. // Bottom
  6914. vertices.push(new Vec3(-radiusBottom * sin(theta), -height * 0.5, radiusBottom * cos(theta)));
  6915. bottomface.push(2 * i + 2); // Top
  6916. vertices.push(new Vec3(-radiusTop * sin(theta), height * 0.5, radiusTop * cos(theta)));
  6917. topface.push(2 * i + 3); // Face
  6918. faces.push([2 * i, 2 * i + 1, 2 * i + 3, 2 * i + 2]);
  6919. } else {
  6920. faces.push([2 * i, 2 * i + 1, 1, 0]); // Connect
  6921. } // Axis: we can cut off half of them if we have even number of segments
  6922. if (N % 2 === 1 || i < N / 2) {
  6923. axes.push(new Vec3(-sin(thetaN), 0, cos(thetaN)));
  6924. }
  6925. }
  6926. faces.push(bottomface);
  6927. axes.push(new Vec3(0, 1, 0)); // Reorder top face
  6928. const temp = [];
  6929. for (let i = 0; i < topface.length; i++) {
  6930. temp.push(topface[topface.length - i - 1]);
  6931. }
  6932. faces.push(temp);
  6933. super({
  6934. vertices,
  6935. faces,
  6936. axes
  6937. });
  6938. this.radiusTop = void 0;
  6939. this.radiusBottom = void 0;
  6940. this.height = void 0;
  6941. this.numSegments = void 0;
  6942. this.type = Shape.types.CYLINDER;
  6943. this.radiusTop = radiusTop;
  6944. this.radiusBottom = radiusBottom;
  6945. this.height = height;
  6946. this.numSegments = numSegments;
  6947. }
  6948. }
  6949. /**
  6950. * Particle shape.
  6951. * @example
  6952. * const particleShape = new CANNON.Particle()
  6953. * const particleBody = new CANNON.Body({ mass: 1, shape: particleShape })
  6954. * world.addBody(particleBody)
  6955. */
  6956. class Particle extends Shape {
  6957. constructor() {
  6958. super({
  6959. type: Shape.types.PARTICLE
  6960. });
  6961. }
  6962. /**
  6963. * calculateLocalInertia
  6964. */
  6965. calculateLocalInertia(mass, target = new Vec3()) {
  6966. target.set(0, 0, 0);
  6967. return target;
  6968. }
  6969. volume() {
  6970. return 0;
  6971. }
  6972. updateBoundingSphereRadius() {
  6973. this.boundingSphereRadius = 0;
  6974. }
  6975. calculateWorldAABB(pos, quat, min, max) {
  6976. // Get each axis max
  6977. min.copy(pos);
  6978. max.copy(pos);
  6979. }
  6980. }
  6981. /**
  6982. * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos.
  6983. * @example
  6984. * const planeShape = new CANNON.Plane()
  6985. * const planeBody = new CANNON.Body({ mass: 0, shape: planeShape })
  6986. * planeBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0) // make it face up
  6987. * world.addBody(planeBody)
  6988. */
  6989. class Plane extends Shape {
  6990. /** worldNormal */
  6991. /** worldNormalNeedsUpdate */
  6992. constructor() {
  6993. super({
  6994. type: Shape.types.PLANE
  6995. }); // World oriented normal
  6996. this.worldNormal = void 0;
  6997. this.worldNormalNeedsUpdate = void 0;
  6998. this.boundingSphereRadius = void 0;
  6999. this.worldNormal = new Vec3();
  7000. this.worldNormalNeedsUpdate = true;
  7001. this.boundingSphereRadius = Number.MAX_VALUE;
  7002. }
  7003. /** computeWorldNormal */
  7004. computeWorldNormal(quat) {
  7005. const n = this.worldNormal;
  7006. n.set(0, 0, 1);
  7007. quat.vmult(n, n);
  7008. this.worldNormalNeedsUpdate = false;
  7009. }
  7010. calculateLocalInertia(mass, target = new Vec3()) {
  7011. return target;
  7012. }
  7013. volume() {
  7014. return (// The plane is infinite...
  7015. Number.MAX_VALUE
  7016. );
  7017. }
  7018. calculateWorldAABB(pos, quat, min, max) {
  7019. // The plane AABB is infinite, except if the normal is pointing along any axis
  7020. tempNormal.set(0, 0, 1); // Default plane normal is z
  7021. quat.vmult(tempNormal, tempNormal);
  7022. const maxVal = Number.MAX_VALUE;
  7023. min.set(-maxVal, -maxVal, -maxVal);
  7024. max.set(maxVal, maxVal, maxVal);
  7025. if (tempNormal.x === 1) {
  7026. max.x = pos.x;
  7027. } else if (tempNormal.x === -1) {
  7028. min.x = pos.x;
  7029. }
  7030. if (tempNormal.y === 1) {
  7031. max.y = pos.y;
  7032. } else if (tempNormal.y === -1) {
  7033. min.y = pos.y;
  7034. }
  7035. if (tempNormal.z === 1) {
  7036. max.z = pos.z;
  7037. } else if (tempNormal.z === -1) {
  7038. min.z = pos.z;
  7039. }
  7040. }
  7041. updateBoundingSphereRadius() {
  7042. this.boundingSphereRadius = Number.MAX_VALUE;
  7043. }
  7044. }
  7045. const tempNormal = new Vec3();
  7046. /**
  7047. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  7048. * @todo Should be possible to use along all axes, not just y
  7049. * @todo should be possible to scale along all axes
  7050. * @todo Refactor elementSize to elementSizeX and elementSizeY
  7051. *
  7052. * @example
  7053. * // Generate some height data (y-values).
  7054. * const data = []
  7055. * for (let i = 0; i < 1000; i++) {
  7056. * const y = 0.5 * Math.cos(0.2 * i)
  7057. * data.push(y)
  7058. * }
  7059. *
  7060. * // Create the heightfield shape
  7061. * const heightfieldShape = new CANNON.Heightfield(data, {
  7062. * elementSize: 1 // Distance between the data points in X and Y directions
  7063. * })
  7064. * const heightfieldBody = new CANNON.Body({ shape: heightfieldShape })
  7065. * world.addBody(heightfieldBody)
  7066. */
  7067. class Heightfield extends Shape {
  7068. /**
  7069. * An array of numbers, or height values, that are spread out along the x axis.
  7070. */
  7071. /**
  7072. * Max value of the data points in the data array.
  7073. */
  7074. /**
  7075. * Minimum value of the data points in the data array.
  7076. */
  7077. /**
  7078. * World spacing between the data points in X and Y direction.
  7079. * @todo elementSizeX and Y
  7080. * @default 1
  7081. */
  7082. /**
  7083. * @default true
  7084. */
  7085. /**
  7086. * @param data An array of numbers, or height values, that are spread out along the x axis.
  7087. */
  7088. constructor(data, options = {}) {
  7089. options = Utils.defaults(options, {
  7090. maxValue: null,
  7091. minValue: null,
  7092. elementSize: 1
  7093. });
  7094. super({
  7095. type: Shape.types.HEIGHTFIELD
  7096. });
  7097. this.data = void 0;
  7098. this.maxValue = void 0;
  7099. this.minValue = void 0;
  7100. this.elementSize = void 0;
  7101. this.cacheEnabled = void 0;
  7102. this.pillarConvex = void 0;
  7103. this.pillarOffset = void 0;
  7104. this._cachedPillars = void 0;
  7105. this.data = data;
  7106. this.maxValue = options.maxValue;
  7107. this.minValue = options.minValue;
  7108. this.elementSize = options.elementSize;
  7109. if (options.minValue === null) {
  7110. this.updateMinValue();
  7111. }
  7112. if (options.maxValue === null) {
  7113. this.updateMaxValue();
  7114. }
  7115. this.cacheEnabled = true;
  7116. this.pillarConvex = new ConvexPolyhedron();
  7117. this.pillarOffset = new Vec3();
  7118. this.updateBoundingSphereRadius(); // "i_j_isUpper" => { convex: ..., offset: ... }
  7119. // for example:
  7120. // _cachedPillars["0_2_1"]
  7121. this._cachedPillars = {};
  7122. }
  7123. /**
  7124. * Call whenever you change the data array.
  7125. */
  7126. update() {
  7127. this._cachedPillars = {};
  7128. }
  7129. /**
  7130. * Update the `minValue` property
  7131. */
  7132. updateMinValue() {
  7133. const data = this.data;
  7134. let minValue = data[0][0];
  7135. for (let i = 0; i !== data.length; i++) {
  7136. for (let j = 0; j !== data[i].length; j++) {
  7137. const v = data[i][j];
  7138. if (v < minValue) {
  7139. minValue = v;
  7140. }
  7141. }
  7142. }
  7143. this.minValue = minValue;
  7144. }
  7145. /**
  7146. * Update the `maxValue` property
  7147. */
  7148. updateMaxValue() {
  7149. const data = this.data;
  7150. let maxValue = data[0][0];
  7151. for (let i = 0; i !== data.length; i++) {
  7152. for (let j = 0; j !== data[i].length; j++) {
  7153. const v = data[i][j];
  7154. if (v > maxValue) {
  7155. maxValue = v;
  7156. }
  7157. }
  7158. }
  7159. this.maxValue = maxValue;
  7160. }
  7161. /**
  7162. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  7163. */
  7164. setHeightValueAtIndex(xi, yi, value) {
  7165. const data = this.data;
  7166. data[xi][yi] = value; // Invalidate cache
  7167. this.clearCachedConvexTrianglePillar(xi, yi, false);
  7168. if (xi > 0) {
  7169. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  7170. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  7171. }
  7172. if (yi > 0) {
  7173. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  7174. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  7175. }
  7176. if (yi > 0 && xi > 0) {
  7177. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  7178. }
  7179. }
  7180. /**
  7181. * Get max/min in a rectangle in the matrix data
  7182. * @param result An array to store the results in.
  7183. * @return The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  7184. */
  7185. getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, result = []) {
  7186. // Get max and min of the data
  7187. const data = this.data; // Set first value
  7188. let max = this.minValue;
  7189. for (let i = iMinX; i <= iMaxX; i++) {
  7190. for (let j = iMinY; j <= iMaxY; j++) {
  7191. const height = data[i][j];
  7192. if (height > max) {
  7193. max = height;
  7194. }
  7195. }
  7196. }
  7197. result[0] = this.minValue;
  7198. result[1] = max;
  7199. }
  7200. /**
  7201. * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
  7202. * @param result Two-element array
  7203. * @param clamp If the position should be clamped to the heightfield edge.
  7204. */
  7205. getIndexOfPosition(x, y, result, clamp) {
  7206. // Get the index of the data points to test against
  7207. const w = this.elementSize;
  7208. const data = this.data;
  7209. let xi = Math.floor(x / w);
  7210. let yi = Math.floor(y / w);
  7211. result[0] = xi;
  7212. result[1] = yi;
  7213. if (clamp) {
  7214. // Clamp index to edges
  7215. if (xi < 0) {
  7216. xi = 0;
  7217. }
  7218. if (yi < 0) {
  7219. yi = 0;
  7220. }
  7221. if (xi >= data.length - 1) {
  7222. xi = data.length - 1;
  7223. }
  7224. if (yi >= data[0].length - 1) {
  7225. yi = data[0].length - 1;
  7226. }
  7227. } // Bail out if we are out of the terrain
  7228. if (xi < 0 || yi < 0 || xi >= data.length - 1 || yi >= data[0].length - 1) {
  7229. return false;
  7230. }
  7231. return true;
  7232. }
  7233. getTriangleAt(x, y, edgeClamp, a, b, c) {
  7234. const idx = getHeightAt_idx;
  7235. this.getIndexOfPosition(x, y, idx, edgeClamp);
  7236. let xi = idx[0];
  7237. let yi = idx[1];
  7238. const data = this.data;
  7239. if (edgeClamp) {
  7240. xi = Math.min(data.length - 2, Math.max(0, xi));
  7241. yi = Math.min(data[0].length - 2, Math.max(0, yi));
  7242. }
  7243. const elementSize = this.elementSize;
  7244. const lowerDist2 = (x / elementSize - xi) ** 2 + (y / elementSize - yi) ** 2;
  7245. const upperDist2 = (x / elementSize - (xi + 1)) ** 2 + (y / elementSize - (yi + 1)) ** 2;
  7246. const upper = lowerDist2 > upperDist2;
  7247. this.getTriangle(xi, yi, upper, a, b, c);
  7248. return upper;
  7249. }
  7250. getNormalAt(x, y, edgeClamp, result) {
  7251. const a = getNormalAt_a;
  7252. const b = getNormalAt_b;
  7253. const c = getNormalAt_c;
  7254. const e0 = getNormalAt_e0;
  7255. const e1 = getNormalAt_e1;
  7256. this.getTriangleAt(x, y, edgeClamp, a, b, c);
  7257. b.vsub(a, e0);
  7258. c.vsub(a, e1);
  7259. e0.cross(e1, result);
  7260. result.normalize();
  7261. }
  7262. /**
  7263. * Get an AABB of a square in the heightfield
  7264. * @param xi
  7265. * @param yi
  7266. * @param result
  7267. */
  7268. getAabbAtIndex(xi, yi, {
  7269. lowerBound,
  7270. upperBound
  7271. }) {
  7272. const data = this.data;
  7273. const elementSize = this.elementSize;
  7274. lowerBound.set(xi * elementSize, yi * elementSize, data[xi][yi]);
  7275. upperBound.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);
  7276. }
  7277. /**
  7278. * Get the height in the heightfield at a given position
  7279. */
  7280. getHeightAt(x, y, edgeClamp) {
  7281. const data = this.data;
  7282. const a = getHeightAt_a;
  7283. const b = getHeightAt_b;
  7284. const c = getHeightAt_c;
  7285. const idx = getHeightAt_idx;
  7286. this.getIndexOfPosition(x, y, idx, edgeClamp);
  7287. let xi = idx[0];
  7288. let yi = idx[1];
  7289. if (edgeClamp) {
  7290. xi = Math.min(data.length - 2, Math.max(0, xi));
  7291. yi = Math.min(data[0].length - 2, Math.max(0, yi));
  7292. }
  7293. const upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);
  7294. barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);
  7295. const w = getHeightAt_weights;
  7296. if (upper) {
  7297. // Top triangle verts
  7298. return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;
  7299. } else {
  7300. // Top triangle verts
  7301. return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;
  7302. }
  7303. }
  7304. getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle) {
  7305. return xi + "_" + yi + "_" + (getUpperTriangle ? 1 : 0);
  7306. }
  7307. getCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7308. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  7309. }
  7310. setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, convex, offset) {
  7311. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  7312. convex,
  7313. offset
  7314. };
  7315. }
  7316. clearCachedConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7317. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  7318. }
  7319. /**
  7320. * Get a triangle from the heightfield
  7321. */
  7322. getTriangle(xi, yi, upper, a, b, c) {
  7323. const data = this.data;
  7324. const elementSize = this.elementSize;
  7325. if (upper) {
  7326. // Top triangle verts
  7327. a.set((xi + 1) * elementSize, (yi + 1) * elementSize, data[xi + 1][yi + 1]);
  7328. b.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);
  7329. c.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);
  7330. } else {
  7331. // Top triangle verts
  7332. a.set(xi * elementSize, yi * elementSize, data[xi][yi]);
  7333. b.set((xi + 1) * elementSize, yi * elementSize, data[xi + 1][yi]);
  7334. c.set(xi * elementSize, (yi + 1) * elementSize, data[xi][yi + 1]);
  7335. }
  7336. }
  7337. /**
  7338. * Get a triangle in the terrain in the form of a triangular convex shape.
  7339. */
  7340. getConvexTrianglePillar(xi, yi, getUpperTriangle) {
  7341. let result = this.pillarConvex;
  7342. let offsetResult = this.pillarOffset;
  7343. if (this.cacheEnabled) {
  7344. const data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  7345. if (data) {
  7346. this.pillarConvex = data.convex;
  7347. this.pillarOffset = data.offset;
  7348. return;
  7349. }
  7350. result = new ConvexPolyhedron();
  7351. offsetResult = new Vec3();
  7352. this.pillarConvex = result;
  7353. this.pillarOffset = offsetResult;
  7354. }
  7355. const data = this.data;
  7356. const elementSize = this.elementSize;
  7357. const faces = result.faces; // Reuse verts if possible
  7358. result.vertices.length = 6;
  7359. for (let i = 0; i < 6; i++) {
  7360. if (!result.vertices[i]) {
  7361. result.vertices[i] = new Vec3();
  7362. }
  7363. } // Reuse faces if possible
  7364. faces.length = 5;
  7365. for (let i = 0; i < 5; i++) {
  7366. if (!faces[i]) {
  7367. faces[i] = [];
  7368. }
  7369. }
  7370. const verts = result.vertices;
  7371. const h = (Math.min(data[xi][yi], data[xi + 1][yi], data[xi][yi + 1], data[xi + 1][yi + 1]) - this.minValue) / 2 + this.minValue;
  7372. if (!getUpperTriangle) {
  7373. // Center of the triangle pillar - all polygons are given relative to this one
  7374. offsetResult.set((xi + 0.25) * elementSize, // sort of center of a triangle
  7375. (yi + 0.25) * elementSize, h // vertical center
  7376. ); // Top triangle verts
  7377. verts[0].set(-0.25 * elementSize, -0.25 * elementSize, data[xi][yi] - h);
  7378. verts[1].set(0.75 * elementSize, -0.25 * elementSize, data[xi + 1][yi] - h);
  7379. verts[2].set(-0.25 * elementSize, 0.75 * elementSize, data[xi][yi + 1] - h); // bottom triangle verts
  7380. verts[3].set(-0.25 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
  7381. verts[4].set(0.75 * elementSize, -0.25 * elementSize, -Math.abs(h) - 1);
  7382. verts[5].set(-0.25 * elementSize, 0.75 * elementSize, -Math.abs(h) - 1); // top triangle
  7383. faces[0][0] = 0;
  7384. faces[0][1] = 1;
  7385. faces[0][2] = 2; // bottom triangle
  7386. faces[1][0] = 5;
  7387. faces[1][1] = 4;
  7388. faces[1][2] = 3; // -x facing quad
  7389. faces[2][0] = 0;
  7390. faces[2][1] = 2;
  7391. faces[2][2] = 5;
  7392. faces[2][3] = 3; // -y facing quad
  7393. faces[3][0] = 1;
  7394. faces[3][1] = 0;
  7395. faces[3][2] = 3;
  7396. faces[3][3] = 4; // +xy facing quad
  7397. faces[4][0] = 4;
  7398. faces[4][1] = 5;
  7399. faces[4][2] = 2;
  7400. faces[4][3] = 1;
  7401. } else {
  7402. // Center of the triangle pillar - all polygons are given relative to this one
  7403. offsetResult.set((xi + 0.75) * elementSize, // sort of center of a triangle
  7404. (yi + 0.75) * elementSize, h // vertical center
  7405. ); // Top triangle verts
  7406. verts[0].set(0.25 * elementSize, 0.25 * elementSize, data[xi + 1][yi + 1] - h);
  7407. verts[1].set(-0.75 * elementSize, 0.25 * elementSize, data[xi][yi + 1] - h);
  7408. verts[2].set(0.25 * elementSize, -0.75 * elementSize, data[xi + 1][yi] - h); // bottom triangle verts
  7409. verts[3].set(0.25 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
  7410. verts[4].set(-0.75 * elementSize, 0.25 * elementSize, -Math.abs(h) - 1);
  7411. verts[5].set(0.25 * elementSize, -0.75 * elementSize, -Math.abs(h) - 1); // Top triangle
  7412. faces[0][0] = 0;
  7413. faces[0][1] = 1;
  7414. faces[0][2] = 2; // bottom triangle
  7415. faces[1][0] = 5;
  7416. faces[1][1] = 4;
  7417. faces[1][2] = 3; // +x facing quad
  7418. faces[2][0] = 2;
  7419. faces[2][1] = 5;
  7420. faces[2][2] = 3;
  7421. faces[2][3] = 0; // +y facing quad
  7422. faces[3][0] = 3;
  7423. faces[3][1] = 4;
  7424. faces[3][2] = 1;
  7425. faces[3][3] = 0; // -xy facing quad
  7426. faces[4][0] = 1;
  7427. faces[4][1] = 4;
  7428. faces[4][2] = 5;
  7429. faces[4][3] = 2;
  7430. }
  7431. result.computeNormals();
  7432. result.computeEdges();
  7433. result.updateBoundingSphereRadius();
  7434. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  7435. }
  7436. calculateLocalInertia(mass, target = new Vec3()) {
  7437. target.set(0, 0, 0);
  7438. return target;
  7439. }
  7440. volume() {
  7441. return (// The terrain is infinite
  7442. Number.MAX_VALUE
  7443. );
  7444. }
  7445. calculateWorldAABB(pos, quat, min, max) {
  7446. /** @TODO do it properly */
  7447. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7448. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7449. }
  7450. updateBoundingSphereRadius() {
  7451. // Use the bounding box of the min/max values
  7452. const data = this.data;
  7453. const s = this.elementSize;
  7454. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).length();
  7455. }
  7456. /**
  7457. * Sets the height values from an image. Currently only supported in browser.
  7458. */
  7459. setHeightsFromImage(image, scale) {
  7460. const {
  7461. x,
  7462. z,
  7463. y
  7464. } = scale;
  7465. const canvas = document.createElement('canvas');
  7466. canvas.width = image.width;
  7467. canvas.height = image.height;
  7468. const context = canvas.getContext('2d');
  7469. context.drawImage(image, 0, 0);
  7470. const imageData = context.getImageData(0, 0, image.width, image.height);
  7471. const matrix = this.data;
  7472. matrix.length = 0;
  7473. this.elementSize = Math.abs(x) / imageData.width;
  7474. for (let i = 0; i < imageData.height; i++) {
  7475. const row = [];
  7476. for (let j = 0; j < imageData.width; j++) {
  7477. const a = imageData.data[(i * imageData.height + j) * 4];
  7478. const b = imageData.data[(i * imageData.height + j) * 4 + 1];
  7479. const c = imageData.data[(i * imageData.height + j) * 4 + 2];
  7480. const height = (a + b + c) / 4 / 255 * z;
  7481. if (x < 0) {
  7482. row.push(height);
  7483. } else {
  7484. row.unshift(height);
  7485. }
  7486. }
  7487. if (y < 0) {
  7488. matrix.unshift(row);
  7489. } else {
  7490. matrix.push(row);
  7491. }
  7492. }
  7493. this.updateMaxValue();
  7494. this.updateMinValue();
  7495. this.update();
  7496. }
  7497. }
  7498. const getHeightAt_idx = [];
  7499. const getHeightAt_weights = new Vec3();
  7500. const getHeightAt_a = new Vec3();
  7501. const getHeightAt_b = new Vec3();
  7502. const getHeightAt_c = new Vec3();
  7503. const getNormalAt_a = new Vec3();
  7504. const getNormalAt_b = new Vec3();
  7505. const getNormalAt_c = new Vec3();
  7506. const getNormalAt_e0 = new Vec3();
  7507. const getNormalAt_e1 = new Vec3(); // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system
  7508. function barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result) {
  7509. result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
  7510. result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
  7511. result.z = 1 - result.x - result.y;
  7512. }
  7513. /**
  7514. * OctreeNode
  7515. */
  7516. class OctreeNode {
  7517. /** The root node */
  7518. /** Boundary of this node */
  7519. /** Contained data at the current node level */
  7520. /** Children to this node */
  7521. constructor(options = {}) {
  7522. this.root = void 0;
  7523. this.aabb = void 0;
  7524. this.data = void 0;
  7525. this.children = void 0;
  7526. this.root = options.root || null;
  7527. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  7528. this.data = [];
  7529. this.children = [];
  7530. }
  7531. /**
  7532. * reset
  7533. */
  7534. reset() {
  7535. this.children.length = this.data.length = 0;
  7536. }
  7537. /**
  7538. * Insert data into this node
  7539. * @return True if successful, otherwise false
  7540. */
  7541. insert(aabb, elementData, level = 0) {
  7542. const nodeData = this.data; // Ignore objects that do not belong in this node
  7543. if (!this.aabb.contains(aabb)) {
  7544. return false; // object cannot be added
  7545. }
  7546. const children = this.children;
  7547. const maxDepth = this.maxDepth || this.root.maxDepth;
  7548. if (level < maxDepth) {
  7549. // Subdivide if there are no children yet
  7550. let subdivided = false;
  7551. if (!children.length) {
  7552. this.subdivide();
  7553. subdivided = true;
  7554. } // add to whichever node will accept it
  7555. for (let i = 0; i !== 8; i++) {
  7556. if (children[i].insert(aabb, elementData, level + 1)) {
  7557. return true;
  7558. }
  7559. }
  7560. if (subdivided) {
  7561. // No children accepted! Might as well just remove em since they contain none
  7562. children.length = 0;
  7563. }
  7564. } // Too deep, or children didnt want it. add it in current node
  7565. nodeData.push(elementData);
  7566. return true;
  7567. }
  7568. /**
  7569. * Create 8 equally sized children nodes and put them in the `children` array.
  7570. */
  7571. subdivide() {
  7572. const aabb = this.aabb;
  7573. const l = aabb.lowerBound;
  7574. const u = aabb.upperBound;
  7575. const children = this.children;
  7576. children.push(new OctreeNode({
  7577. aabb: new AABB({
  7578. lowerBound: new Vec3(0, 0, 0)
  7579. })
  7580. }), new OctreeNode({
  7581. aabb: new AABB({
  7582. lowerBound: new Vec3(1, 0, 0)
  7583. })
  7584. }), new OctreeNode({
  7585. aabb: new AABB({
  7586. lowerBound: new Vec3(1, 1, 0)
  7587. })
  7588. }), new OctreeNode({
  7589. aabb: new AABB({
  7590. lowerBound: new Vec3(1, 1, 1)
  7591. })
  7592. }), new OctreeNode({
  7593. aabb: new AABB({
  7594. lowerBound: new Vec3(0, 1, 1)
  7595. })
  7596. }), new OctreeNode({
  7597. aabb: new AABB({
  7598. lowerBound: new Vec3(0, 0, 1)
  7599. })
  7600. }), new OctreeNode({
  7601. aabb: new AABB({
  7602. lowerBound: new Vec3(1, 0, 1)
  7603. })
  7604. }), new OctreeNode({
  7605. aabb: new AABB({
  7606. lowerBound: new Vec3(0, 1, 0)
  7607. })
  7608. }));
  7609. u.vsub(l, halfDiagonal);
  7610. halfDiagonal.scale(0.5, halfDiagonal);
  7611. const root = this.root || this;
  7612. for (let i = 0; i !== 8; i++) {
  7613. const child = children[i]; // Set current node as root
  7614. child.root = root; // Compute bounds
  7615. const lowerBound = child.aabb.lowerBound;
  7616. lowerBound.x *= halfDiagonal.x;
  7617. lowerBound.y *= halfDiagonal.y;
  7618. lowerBound.z *= halfDiagonal.z;
  7619. lowerBound.vadd(l, lowerBound); // Upper bound is always lower bound + halfDiagonal
  7620. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  7621. }
  7622. }
  7623. /**
  7624. * Get all data, potentially within an AABB
  7625. * @return The "result" object
  7626. */
  7627. aabbQuery(aabb, result) {
  7628. this.data; // abort if the range does not intersect this node
  7629. // if (!this.aabb.overlaps(aabb)){
  7630. // return result;
  7631. // }
  7632. // Add objects at this level
  7633. // Array.prototype.push.apply(result, nodeData);
  7634. // Add child data
  7635. // @todo unwrap recursion into a queue / loop, that's faster in JS
  7636. this.children; // for (let i = 0, N = this.children.length; i !== N; i++) {
  7637. // children[i].aabbQuery(aabb, result);
  7638. // }
  7639. const queue = [this];
  7640. while (queue.length) {
  7641. const node = queue.pop();
  7642. if (node.aabb.overlaps(aabb)) {
  7643. Array.prototype.push.apply(result, node.data);
  7644. }
  7645. Array.prototype.push.apply(queue, node.children);
  7646. }
  7647. return result;
  7648. }
  7649. /**
  7650. * Get all data, potentially intersected by a ray.
  7651. * @return The "result" object
  7652. */
  7653. rayQuery(ray, treeTransform, result) {
  7654. // Use aabb query for now.
  7655. /** @todo implement real ray query which needs less lookups */
  7656. ray.getAABB(tmpAABB);
  7657. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  7658. this.aabbQuery(tmpAABB, result);
  7659. return result;
  7660. }
  7661. /**
  7662. * removeEmptyNodes
  7663. */
  7664. removeEmptyNodes() {
  7665. for (let i = this.children.length - 1; i >= 0; i--) {
  7666. this.children[i].removeEmptyNodes();
  7667. if (!this.children[i].children.length && !this.children[i].data.length) {
  7668. this.children.splice(i, 1);
  7669. }
  7670. }
  7671. }
  7672. }
  7673. /**
  7674. * Octree
  7675. */
  7676. class Octree extends OctreeNode {
  7677. /**
  7678. * Maximum subdivision depth
  7679. * @default 8
  7680. */
  7681. /**
  7682. * @param aabb The total AABB of the tree
  7683. */
  7684. constructor(aabb, options = {}) {
  7685. super({
  7686. root: null,
  7687. aabb
  7688. });
  7689. this.maxDepth = void 0;
  7690. this.maxDepth = typeof options.maxDepth !== 'undefined' ? options.maxDepth : 8;
  7691. }
  7692. }
  7693. const halfDiagonal = new Vec3();
  7694. const tmpAABB = new AABB();
  7695. /**
  7696. * Trimesh.
  7697. * @example
  7698. * // How to make a mesh with a single triangle
  7699. * const vertices = [
  7700. * 0, 0, 0, // vertex 0
  7701. * 1, 0, 0, // vertex 1
  7702. * 0, 1, 0 // vertex 2
  7703. * ]
  7704. * const indices = [
  7705. * 0, 1, 2 // triangle 0
  7706. * ]
  7707. * const trimeshShape = new CANNON.Trimesh(vertices, indices)
  7708. */
  7709. class Trimesh extends Shape {
  7710. /**
  7711. * vertices
  7712. */
  7713. /**
  7714. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  7715. */
  7716. /**
  7717. * The normals data.
  7718. */
  7719. /**
  7720. * The local AABB of the mesh.
  7721. */
  7722. /**
  7723. * References to vertex pairs, making up all unique edges in the trimesh.
  7724. */
  7725. /**
  7726. * Local scaling of the mesh. Use .setScale() to set it.
  7727. */
  7728. /**
  7729. * The indexed triangles. Use .updateTree() to update it.
  7730. */
  7731. constructor(vertices, indices) {
  7732. super({
  7733. type: Shape.types.TRIMESH
  7734. });
  7735. this.vertices = void 0;
  7736. this.indices = void 0;
  7737. this.normals = void 0;
  7738. this.aabb = void 0;
  7739. this.edges = void 0;
  7740. this.scale = void 0;
  7741. this.tree = void 0;
  7742. this.vertices = new Float32Array(vertices);
  7743. this.indices = new Int16Array(indices);
  7744. this.normals = new Float32Array(indices.length);
  7745. this.aabb = new AABB();
  7746. this.edges = null;
  7747. this.scale = new Vec3(1, 1, 1);
  7748. this.tree = new Octree();
  7749. this.updateEdges();
  7750. this.updateNormals();
  7751. this.updateAABB();
  7752. this.updateBoundingSphereRadius();
  7753. this.updateTree();
  7754. }
  7755. /**
  7756. * updateTree
  7757. */
  7758. updateTree() {
  7759. const tree = this.tree;
  7760. tree.reset();
  7761. tree.aabb.copy(this.aabb);
  7762. const scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  7763. tree.aabb.lowerBound.x *= 1 / scale.x;
  7764. tree.aabb.lowerBound.y *= 1 / scale.y;
  7765. tree.aabb.lowerBound.z *= 1 / scale.z;
  7766. tree.aabb.upperBound.x *= 1 / scale.x;
  7767. tree.aabb.upperBound.y *= 1 / scale.y;
  7768. tree.aabb.upperBound.z *= 1 / scale.z; // Insert all triangles
  7769. const triangleAABB = new AABB();
  7770. const a = new Vec3();
  7771. const b = new Vec3();
  7772. const c = new Vec3();
  7773. const points = [a, b, c];
  7774. for (let i = 0; i < this.indices.length / 3; i++) {
  7775. //this.getTriangleVertices(i, a, b, c);
  7776. // Get unscaled triangle verts
  7777. const i3 = i * 3;
  7778. this._getUnscaledVertex(this.indices[i3], a);
  7779. this._getUnscaledVertex(this.indices[i3 + 1], b);
  7780. this._getUnscaledVertex(this.indices[i3 + 2], c);
  7781. triangleAABB.setFromPoints(points);
  7782. tree.insert(triangleAABB, i);
  7783. }
  7784. tree.removeEmptyNodes();
  7785. }
  7786. /**
  7787. * Get triangles in a local AABB from the trimesh.
  7788. * @param result An array of integers, referencing the queried triangles.
  7789. */
  7790. getTrianglesInAABB(aabb, result) {
  7791. unscaledAABB.copy(aabb); // Scale it to local
  7792. const scale = this.scale;
  7793. const isx = scale.x;
  7794. const isy = scale.y;
  7795. const isz = scale.z;
  7796. const l = unscaledAABB.lowerBound;
  7797. const u = unscaledAABB.upperBound;
  7798. l.x /= isx;
  7799. l.y /= isy;
  7800. l.z /= isz;
  7801. u.x /= isx;
  7802. u.y /= isy;
  7803. u.z /= isz;
  7804. return this.tree.aabbQuery(unscaledAABB, result);
  7805. }
  7806. /**
  7807. * setScale
  7808. */
  7809. setScale(scale) {
  7810. const wasUniform = this.scale.x === this.scale.y && this.scale.y === this.scale.z;
  7811. const isUniform = scale.x === scale.y && scale.y === scale.z;
  7812. if (!(wasUniform && isUniform)) {
  7813. // Non-uniform scaling. Need to update normals.
  7814. this.updateNormals();
  7815. }
  7816. this.scale.copy(scale);
  7817. this.updateAABB();
  7818. this.updateBoundingSphereRadius();
  7819. }
  7820. /**
  7821. * Compute the normals of the faces. Will save in the `.normals` array.
  7822. */
  7823. updateNormals() {
  7824. const n = computeNormals_n; // Generate normals
  7825. const normals = this.normals;
  7826. for (let i = 0; i < this.indices.length / 3; i++) {
  7827. const i3 = i * 3;
  7828. const a = this.indices[i3];
  7829. const b = this.indices[i3 + 1];
  7830. const c = this.indices[i3 + 2];
  7831. this.getVertex(a, va);
  7832. this.getVertex(b, vb);
  7833. this.getVertex(c, vc);
  7834. Trimesh.computeNormal(vb, va, vc, n);
  7835. normals[i3] = n.x;
  7836. normals[i3 + 1] = n.y;
  7837. normals[i3 + 2] = n.z;
  7838. }
  7839. }
  7840. /**
  7841. * Update the `.edges` property
  7842. */
  7843. updateEdges() {
  7844. const edges = {};
  7845. const add = (a, b) => {
  7846. const key = a < b ? a + "_" + b : b + "_" + a;
  7847. edges[key] = true;
  7848. };
  7849. for (let i = 0; i < this.indices.length / 3; i++) {
  7850. const i3 = i * 3;
  7851. const a = this.indices[i3];
  7852. const b = this.indices[i3 + 1];
  7853. const c = this.indices[i3 + 2];
  7854. add(a, b);
  7855. add(b, c);
  7856. add(c, a);
  7857. }
  7858. const keys = Object.keys(edges);
  7859. this.edges = new Int16Array(keys.length * 2);
  7860. for (let i = 0; i < keys.length; i++) {
  7861. const indices = keys[i].split('_');
  7862. this.edges[2 * i] = parseInt(indices[0], 10);
  7863. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  7864. }
  7865. }
  7866. /**
  7867. * Get an edge vertex
  7868. * @param firstOrSecond 0 or 1, depending on which one of the vertices you need.
  7869. * @param vertexStore Where to store the result
  7870. */
  7871. getEdgeVertex(edgeIndex, firstOrSecond, vertexStore) {
  7872. const vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  7873. this.getVertex(vertexIndex, vertexStore);
  7874. }
  7875. /**
  7876. * Get a vector along an edge.
  7877. */
  7878. getEdgeVector(edgeIndex, vectorStore) {
  7879. const va = getEdgeVector_va;
  7880. const vb = getEdgeVector_vb;
  7881. this.getEdgeVertex(edgeIndex, 0, va);
  7882. this.getEdgeVertex(edgeIndex, 1, vb);
  7883. vb.vsub(va, vectorStore);
  7884. }
  7885. /**
  7886. * Get face normal given 3 vertices
  7887. */
  7888. static computeNormal(va, vb, vc, target) {
  7889. vb.vsub(va, ab);
  7890. vc.vsub(vb, cb);
  7891. cb.cross(ab, target);
  7892. if (!target.isZero()) {
  7893. target.normalize();
  7894. }
  7895. }
  7896. /**
  7897. * Get vertex i.
  7898. * @return The "out" vector object
  7899. */
  7900. getVertex(i, out) {
  7901. const scale = this.scale;
  7902. this._getUnscaledVertex(i, out);
  7903. out.x *= scale.x;
  7904. out.y *= scale.y;
  7905. out.z *= scale.z;
  7906. return out;
  7907. }
  7908. /**
  7909. * Get raw vertex i
  7910. * @return The "out" vector object
  7911. */
  7912. _getUnscaledVertex(i, out) {
  7913. const i3 = i * 3;
  7914. const vertices = this.vertices;
  7915. return out.set(vertices[i3], vertices[i3 + 1], vertices[i3 + 2]);
  7916. }
  7917. /**
  7918. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  7919. * @return The "out" vector object
  7920. */
  7921. getWorldVertex(i, pos, quat, out) {
  7922. this.getVertex(i, out);
  7923. Transform.pointToWorldFrame(pos, quat, out, out);
  7924. return out;
  7925. }
  7926. /**
  7927. * Get the three vertices for triangle i.
  7928. */
  7929. getTriangleVertices(i, a, b, c) {
  7930. const i3 = i * 3;
  7931. this.getVertex(this.indices[i3], a);
  7932. this.getVertex(this.indices[i3 + 1], b);
  7933. this.getVertex(this.indices[i3 + 2], c);
  7934. }
  7935. /**
  7936. * Compute the normal of triangle i.
  7937. * @return The "target" vector object
  7938. */
  7939. getNormal(i, target) {
  7940. const i3 = i * 3;
  7941. return target.set(this.normals[i3], this.normals[i3 + 1], this.normals[i3 + 2]);
  7942. }
  7943. /**
  7944. * @return The "target" vector object
  7945. */
  7946. calculateLocalInertia(mass, target) {
  7947. // Approximate with box inertia
  7948. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  7949. this.computeLocalAABB(cli_aabb);
  7950. const x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x;
  7951. const y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y;
  7952. const z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  7953. return target.set(1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * x * 2 * x + 2 * z * 2 * z), 1.0 / 12.0 * mass * (2 * y * 2 * y + 2 * x * 2 * x));
  7954. }
  7955. /**
  7956. * Compute the local AABB for the trimesh
  7957. */
  7958. computeLocalAABB(aabb) {
  7959. const l = aabb.lowerBound;
  7960. const u = aabb.upperBound;
  7961. const n = this.vertices.length;
  7962. this.vertices;
  7963. const v = computeLocalAABB_worldVert;
  7964. this.getVertex(0, v);
  7965. l.copy(v);
  7966. u.copy(v);
  7967. for (let i = 0; i !== n; i++) {
  7968. this.getVertex(i, v);
  7969. if (v.x < l.x) {
  7970. l.x = v.x;
  7971. } else if (v.x > u.x) {
  7972. u.x = v.x;
  7973. }
  7974. if (v.y < l.y) {
  7975. l.y = v.y;
  7976. } else if (v.y > u.y) {
  7977. u.y = v.y;
  7978. }
  7979. if (v.z < l.z) {
  7980. l.z = v.z;
  7981. } else if (v.z > u.z) {
  7982. u.z = v.z;
  7983. }
  7984. }
  7985. }
  7986. /**
  7987. * Update the `.aabb` property
  7988. */
  7989. updateAABB() {
  7990. this.computeLocalAABB(this.aabb);
  7991. }
  7992. /**
  7993. * Will update the `.boundingSphereRadius` property
  7994. */
  7995. updateBoundingSphereRadius() {
  7996. // Assume points are distributed with local (0,0,0) as center
  7997. let max2 = 0;
  7998. const vertices = this.vertices;
  7999. const v = new Vec3();
  8000. for (let i = 0, N = vertices.length / 3; i !== N; i++) {
  8001. this.getVertex(i, v);
  8002. const norm2 = v.lengthSquared();
  8003. if (norm2 > max2) {
  8004. max2 = norm2;
  8005. }
  8006. }
  8007. this.boundingSphereRadius = Math.sqrt(max2);
  8008. }
  8009. /**
  8010. * calculateWorldAABB
  8011. */
  8012. calculateWorldAABB(pos, quat, min, max) {
  8013. /*
  8014. const n = this.vertices.length / 3,
  8015. verts = this.vertices;
  8016. const minx,miny,minz,maxx,maxy,maxz;
  8017. const v = tempWorldVertex;
  8018. for(let i=0; i<n; i++){
  8019. this.getVertex(i, v);
  8020. quat.vmult(v, v);
  8021. pos.vadd(v, v);
  8022. if (v.x < minx || minx===undefined){
  8023. minx = v.x;
  8024. } else if(v.x > maxx || maxx===undefined){
  8025. maxx = v.x;
  8026. }
  8027. if (v.y < miny || miny===undefined){
  8028. miny = v.y;
  8029. } else if(v.y > maxy || maxy===undefined){
  8030. maxy = v.y;
  8031. }
  8032. if (v.z < minz || minz===undefined){
  8033. minz = v.z;
  8034. } else if(v.z > maxz || maxz===undefined){
  8035. maxz = v.z;
  8036. }
  8037. }
  8038. min.set(minx,miny,minz);
  8039. max.set(maxx,maxy,maxz);
  8040. */
  8041. // Faster approximation using local AABB
  8042. const frame = calculateWorldAABB_frame;
  8043. const result = calculateWorldAABB_aabb;
  8044. frame.position = pos;
  8045. frame.quaternion = quat;
  8046. this.aabb.toWorldFrame(frame, result);
  8047. min.copy(result.lowerBound);
  8048. max.copy(result.upperBound);
  8049. }
  8050. /**
  8051. * Get approximate volume
  8052. */
  8053. volume() {
  8054. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  8055. }
  8056. /**
  8057. * Create a Trimesh instance, shaped as a torus.
  8058. */
  8059. static createTorus(radius = 1, tube = 0.5, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  8060. const vertices = [];
  8061. const indices = [];
  8062. for (let j = 0; j <= radialSegments; j++) {
  8063. for (let i = 0; i <= tubularSegments; i++) {
  8064. const u = i / tubularSegments * arc;
  8065. const v = j / radialSegments * Math.PI * 2;
  8066. const x = (radius + tube * Math.cos(v)) * Math.cos(u);
  8067. const y = (radius + tube * Math.cos(v)) * Math.sin(u);
  8068. const z = tube * Math.sin(v);
  8069. vertices.push(x, y, z);
  8070. }
  8071. }
  8072. for (let j = 1; j <= radialSegments; j++) {
  8073. for (let i = 1; i <= tubularSegments; i++) {
  8074. const a = (tubularSegments + 1) * j + i - 1;
  8075. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  8076. const c = (tubularSegments + 1) * (j - 1) + i;
  8077. const d = (tubularSegments + 1) * j + i;
  8078. indices.push(a, b, d);
  8079. indices.push(b, c, d);
  8080. }
  8081. }
  8082. return new Trimesh(vertices, indices);
  8083. }
  8084. }
  8085. const computeNormals_n = new Vec3();
  8086. const unscaledAABB = new AABB();
  8087. const getEdgeVector_va = new Vec3();
  8088. const getEdgeVector_vb = new Vec3();
  8089. const cb = new Vec3();
  8090. const ab = new Vec3();
  8091. const va = new Vec3();
  8092. const vb = new Vec3();
  8093. const vc = new Vec3();
  8094. const cli_aabb = new AABB();
  8095. const computeLocalAABB_worldVert = new Vec3();
  8096. const calculateWorldAABB_frame = new Transform();
  8097. const calculateWorldAABB_aabb = new AABB();
  8098. /**
  8099. * Constraint equation solver base class.
  8100. */
  8101. class Solver {
  8102. /**
  8103. * All equations to be solved
  8104. */
  8105. /**
  8106. * @todo remove useless constructor
  8107. */
  8108. constructor() {
  8109. this.equations = void 0;
  8110. this.equations = [];
  8111. }
  8112. /**
  8113. * Should be implemented in subclasses!
  8114. * @todo use abstract
  8115. * @return number of iterations performed
  8116. */
  8117. solve(dt, world) {
  8118. return (// Should return the number of iterations done!
  8119. 0
  8120. );
  8121. }
  8122. /**
  8123. * Add an equation
  8124. */
  8125. addEquation(eq) {
  8126. if (eq.enabled && !eq.bi.isTrigger && !eq.bj.isTrigger) {
  8127. this.equations.push(eq);
  8128. }
  8129. }
  8130. /**
  8131. * Remove an equation
  8132. */
  8133. removeEquation(eq) {
  8134. const eqs = this.equations;
  8135. const i = eqs.indexOf(eq);
  8136. if (i !== -1) {
  8137. eqs.splice(i, 1);
  8138. }
  8139. }
  8140. /**
  8141. * Add all equations
  8142. */
  8143. removeAllEquations() {
  8144. this.equations.length = 0;
  8145. }
  8146. }
  8147. /**
  8148. * Constraint equation Gauss-Seidel solver.
  8149. * @todo The spook parameters should be specified for each constraint, not globally.
  8150. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  8151. */
  8152. class GSSolver extends Solver {
  8153. /**
  8154. * The number of solver iterations determines quality of the constraints in the world.
  8155. * The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
  8156. */
  8157. /**
  8158. * When tolerance is reached, the system is assumed to be converged.
  8159. */
  8160. /**
  8161. * @todo remove useless constructor
  8162. */
  8163. constructor() {
  8164. super();
  8165. this.iterations = void 0;
  8166. this.tolerance = void 0;
  8167. this.iterations = 10;
  8168. this.tolerance = 1e-7;
  8169. }
  8170. /**
  8171. * Solve
  8172. * @return number of iterations performed
  8173. */
  8174. solve(dt, world) {
  8175. let iter = 0;
  8176. const maxIter = this.iterations;
  8177. const tolSquared = this.tolerance * this.tolerance;
  8178. const equations = this.equations;
  8179. const Neq = equations.length;
  8180. const bodies = world.bodies;
  8181. const Nbodies = bodies.length;
  8182. const h = dt;
  8183. let B;
  8184. let invC;
  8185. let deltalambda;
  8186. let deltalambdaTot;
  8187. let GWlambda;
  8188. let lambdaj; // Update solve mass
  8189. if (Neq !== 0) {
  8190. for (let i = 0; i !== Nbodies; i++) {
  8191. bodies[i].updateSolveMassProperties();
  8192. }
  8193. } // Things that do not change during iteration can be computed once
  8194. const invCs = GSSolver_solve_invCs;
  8195. const Bs = GSSolver_solve_Bs;
  8196. const lambda = GSSolver_solve_lambda;
  8197. invCs.length = Neq;
  8198. Bs.length = Neq;
  8199. lambda.length = Neq;
  8200. for (let i = 0; i !== Neq; i++) {
  8201. const c = equations[i];
  8202. lambda[i] = 0.0;
  8203. Bs[i] = c.computeB(h);
  8204. invCs[i] = 1.0 / c.computeC();
  8205. }
  8206. if (Neq !== 0) {
  8207. // Reset vlambda
  8208. for (let i = 0; i !== Nbodies; i++) {
  8209. const b = bodies[i];
  8210. const vlambda = b.vlambda;
  8211. const wlambda = b.wlambda;
  8212. vlambda.set(0, 0, 0);
  8213. wlambda.set(0, 0, 0);
  8214. } // Iterate over equations
  8215. for (iter = 0; iter !== maxIter; iter++) {
  8216. // Accumulate the total error for each iteration.
  8217. deltalambdaTot = 0.0;
  8218. for (let j = 0; j !== Neq; j++) {
  8219. const c = equations[j]; // Compute iteration
  8220. B = Bs[j];
  8221. invC = invCs[j];
  8222. lambdaj = lambda[j];
  8223. GWlambda = c.computeGWlambda();
  8224. deltalambda = invC * (B - GWlambda - c.eps * lambdaj); // Clamp if we are not within the min/max interval
  8225. if (lambdaj + deltalambda < c.minForce) {
  8226. deltalambda = c.minForce - lambdaj;
  8227. } else if (lambdaj + deltalambda > c.maxForce) {
  8228. deltalambda = c.maxForce - lambdaj;
  8229. }
  8230. lambda[j] += deltalambda;
  8231. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  8232. c.addToWlambda(deltalambda);
  8233. } // If the total error is small enough - stop iterate
  8234. if (deltalambdaTot * deltalambdaTot < tolSquared) {
  8235. break;
  8236. }
  8237. } // Add result to velocity
  8238. for (let i = 0; i !== Nbodies; i++) {
  8239. const b = bodies[i];
  8240. const v = b.velocity;
  8241. const w = b.angularVelocity;
  8242. b.vlambda.vmul(b.linearFactor, b.vlambda);
  8243. v.vadd(b.vlambda, v);
  8244. b.wlambda.vmul(b.angularFactor, b.wlambda);
  8245. w.vadd(b.wlambda, w);
  8246. } // Set the `.multiplier` property of each equation
  8247. let l = equations.length;
  8248. const invDt = 1 / h;
  8249. while (l--) {
  8250. equations[l].multiplier = lambda[l] * invDt;
  8251. }
  8252. }
  8253. return iter;
  8254. }
  8255. } // Just temporary number holders that we want to reuse each iteration.
  8256. const GSSolver_solve_lambda = [];
  8257. const GSSolver_solve_invCs = [];
  8258. const GSSolver_solve_Bs = [];
  8259. /**
  8260. * Splits the equations into islands and solves them independently. Can improve performance.
  8261. */
  8262. class SplitSolver extends Solver {
  8263. /**
  8264. * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
  8265. */
  8266. /**
  8267. * When tolerance is reached, the system is assumed to be converged.
  8268. */
  8269. /** subsolver */
  8270. constructor(subsolver) {
  8271. super();
  8272. this.iterations = void 0;
  8273. this.tolerance = void 0;
  8274. this.subsolver = void 0;
  8275. this.nodes = void 0;
  8276. this.nodePool = void 0;
  8277. this.iterations = 10;
  8278. this.tolerance = 1e-7;
  8279. this.subsolver = subsolver;
  8280. this.nodes = [];
  8281. this.nodePool = []; // Create needed nodes, reuse if possible
  8282. while (this.nodePool.length < 128) {
  8283. this.nodePool.push(this.createNode());
  8284. }
  8285. }
  8286. /**
  8287. * createNode
  8288. */
  8289. createNode() {
  8290. return {
  8291. body: null,
  8292. children: [],
  8293. eqs: [],
  8294. visited: false
  8295. };
  8296. }
  8297. /**
  8298. * Solve the subsystems
  8299. * @return number of iterations performed
  8300. */
  8301. solve(dt, world) {
  8302. const nodes = SplitSolver_solve_nodes;
  8303. const nodePool = this.nodePool;
  8304. const bodies = world.bodies;
  8305. const equations = this.equations;
  8306. const Neq = equations.length;
  8307. const Nbodies = bodies.length;
  8308. const subsolver = this.subsolver; // Create needed nodes, reuse if possible
  8309. while (nodePool.length < Nbodies) {
  8310. nodePool.push(this.createNode());
  8311. }
  8312. nodes.length = Nbodies;
  8313. for (let i = 0; i < Nbodies; i++) {
  8314. nodes[i] = nodePool[i];
  8315. } // Reset node values
  8316. for (let i = 0; i !== Nbodies; i++) {
  8317. const node = nodes[i];
  8318. node.body = bodies[i];
  8319. node.children.length = 0;
  8320. node.eqs.length = 0;
  8321. node.visited = false;
  8322. }
  8323. for (let k = 0; k !== Neq; k++) {
  8324. const eq = equations[k];
  8325. const i = bodies.indexOf(eq.bi);
  8326. const j = bodies.indexOf(eq.bj);
  8327. const ni = nodes[i];
  8328. const nj = nodes[j];
  8329. ni.children.push(nj);
  8330. ni.eqs.push(eq);
  8331. nj.children.push(ni);
  8332. nj.eqs.push(eq);
  8333. }
  8334. let child;
  8335. let n = 0;
  8336. let eqs = SplitSolver_solve_eqs;
  8337. subsolver.tolerance = this.tolerance;
  8338. subsolver.iterations = this.iterations;
  8339. const dummyWorld = SplitSolver_solve_dummyWorld;
  8340. while (child = getUnvisitedNode(nodes)) {
  8341. eqs.length = 0;
  8342. dummyWorld.bodies.length = 0;
  8343. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  8344. const Neqs = eqs.length;
  8345. eqs = eqs.sort(sortById);
  8346. for (let i = 0; i !== Neqs; i++) {
  8347. subsolver.addEquation(eqs[i]);
  8348. }
  8349. subsolver.solve(dt, dummyWorld);
  8350. subsolver.removeAllEquations();
  8351. n++;
  8352. }
  8353. return n;
  8354. }
  8355. } // Returns the number of subsystems
  8356. const SplitSolver_solve_nodes = []; // All allocated node objects
  8357. const SplitSolver_solve_eqs = []; // Temp array
  8358. const SplitSolver_solve_dummyWorld = {
  8359. bodies: []
  8360. }; // Temp object
  8361. const STATIC = Body.STATIC;
  8362. function getUnvisitedNode(nodes) {
  8363. const Nnodes = nodes.length;
  8364. for (let i = 0; i !== Nnodes; i++) {
  8365. const node = nodes[i];
  8366. if (!node.visited && !(node.body.type & STATIC)) {
  8367. return node;
  8368. }
  8369. }
  8370. return false;
  8371. }
  8372. const queue = [];
  8373. function bfs(root, visitFunc, bds, eqs) {
  8374. queue.push(root);
  8375. root.visited = true;
  8376. visitFunc(root, bds, eqs);
  8377. while (queue.length) {
  8378. const node = queue.pop(); // Loop over unvisited child nodes
  8379. let child;
  8380. while (child = getUnvisitedNode(node.children)) {
  8381. child.visited = true;
  8382. visitFunc(child, bds, eqs);
  8383. queue.push(child);
  8384. }
  8385. }
  8386. }
  8387. function visitFunc(node, bds, eqs) {
  8388. bds.push(node.body);
  8389. const Neqs = node.eqs.length;
  8390. for (let i = 0; i !== Neqs; i++) {
  8391. const eq = node.eqs[i];
  8392. if (!eqs.includes(eq)) {
  8393. eqs.push(eq);
  8394. }
  8395. }
  8396. }
  8397. function sortById(a, b) {
  8398. return b.id - a.id;
  8399. }
  8400. /**
  8401. * For pooling objects that can be reused.
  8402. */
  8403. class Pool {
  8404. constructor() {
  8405. this.objects = [];
  8406. this.type = Object;
  8407. }
  8408. /**
  8409. * Release an object after use
  8410. */
  8411. release(...args) {
  8412. const Nargs = args.length;
  8413. for (let i = 0; i !== Nargs; i++) {
  8414. this.objects.push(args[i]);
  8415. }
  8416. return this;
  8417. }
  8418. /**
  8419. * Get an object
  8420. */
  8421. get() {
  8422. if (this.objects.length === 0) {
  8423. return this.constructObject();
  8424. } else {
  8425. return this.objects.pop();
  8426. }
  8427. }
  8428. /**
  8429. * Construct an object. Should be implemented in each subclass.
  8430. */
  8431. constructObject() {
  8432. throw new Error('constructObject() not implemented in this Pool subclass yet!');
  8433. }
  8434. /**
  8435. * @return Self, for chaining
  8436. */
  8437. resize(size) {
  8438. const objects = this.objects;
  8439. while (objects.length > size) {
  8440. objects.pop();
  8441. }
  8442. while (objects.length < size) {
  8443. objects.push(this.constructObject());
  8444. }
  8445. return this;
  8446. }
  8447. }
  8448. /**
  8449. * Vec3Pool
  8450. */
  8451. class Vec3Pool extends Pool {
  8452. constructor(...args) {
  8453. super(...args);
  8454. this.type = Vec3;
  8455. }
  8456. /**
  8457. * Construct a vector
  8458. */
  8459. constructObject() {
  8460. return new Vec3();
  8461. }
  8462. }
  8463. let _COLLISION_TYPES$sphe, _COLLISION_TYPES$sphe2, _COLLISION_TYPES$boxB, _COLLISION_TYPES$sphe3, _COLLISION_TYPES$plan, _COLLISION_TYPES$conv, _COLLISION_TYPES$sphe4, _COLLISION_TYPES$plan2, _COLLISION_TYPES$boxC, _COLLISION_TYPES$sphe5, _COLLISION_TYPES$boxH, _COLLISION_TYPES$conv2, _COLLISION_TYPES$sphe6, _COLLISION_TYPES$plan3, _COLLISION_TYPES$boxP, _COLLISION_TYPES$conv3, _COLLISION_TYPES$cyli, _COLLISION_TYPES$sphe7, _COLLISION_TYPES$plan4, _COLLISION_TYPES$boxC2, _COLLISION_TYPES$conv4, _COLLISION_TYPES$heig, _COLLISION_TYPES$part, _COLLISION_TYPES$sphe8, _COLLISION_TYPES$plan5;
  8464. // Naming rule: based of the order in SHAPE_TYPES,
  8465. // the first part of the method is formed by the
  8466. // shape type that comes before, in the second part
  8467. // there is the shape type that comes after in the SHAPE_TYPES list
  8468. const COLLISION_TYPES = {
  8469. sphereSphere: Shape.types.SPHERE,
  8470. spherePlane: Shape.types.SPHERE | Shape.types.PLANE,
  8471. boxBox: Shape.types.BOX | Shape.types.BOX,
  8472. sphereBox: Shape.types.SPHERE | Shape.types.BOX,
  8473. planeBox: Shape.types.PLANE | Shape.types.BOX,
  8474. convexConvex: Shape.types.CONVEXPOLYHEDRON,
  8475. sphereConvex: Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON,
  8476. planeConvex: Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON,
  8477. boxConvex: Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON,
  8478. sphereHeightfield: Shape.types.SPHERE | Shape.types.HEIGHTFIELD,
  8479. boxHeightfield: Shape.types.BOX | Shape.types.HEIGHTFIELD,
  8480. convexHeightfield: Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD,
  8481. sphereParticle: Shape.types.PARTICLE | Shape.types.SPHERE,
  8482. planeParticle: Shape.types.PLANE | Shape.types.PARTICLE,
  8483. boxParticle: Shape.types.BOX | Shape.types.PARTICLE,
  8484. convexParticle: Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON,
  8485. cylinderCylinder: Shape.types.CYLINDER,
  8486. sphereCylinder: Shape.types.SPHERE | Shape.types.CYLINDER,
  8487. planeCylinder: Shape.types.PLANE | Shape.types.CYLINDER,
  8488. boxCylinder: Shape.types.BOX | Shape.types.CYLINDER,
  8489. convexCylinder: Shape.types.CONVEXPOLYHEDRON | Shape.types.CYLINDER,
  8490. heightfieldCylinder: Shape.types.HEIGHTFIELD | Shape.types.CYLINDER,
  8491. particleCylinder: Shape.types.PARTICLE | Shape.types.CYLINDER,
  8492. sphereTrimesh: Shape.types.SPHERE | Shape.types.TRIMESH,
  8493. planeTrimesh: Shape.types.PLANE | Shape.types.TRIMESH
  8494. };
  8495. _COLLISION_TYPES$sphe = COLLISION_TYPES.sphereSphere;
  8496. _COLLISION_TYPES$sphe2 = COLLISION_TYPES.spherePlane;
  8497. _COLLISION_TYPES$boxB = COLLISION_TYPES.boxBox;
  8498. _COLLISION_TYPES$sphe3 = COLLISION_TYPES.sphereBox;
  8499. _COLLISION_TYPES$plan = COLLISION_TYPES.planeBox;
  8500. _COLLISION_TYPES$conv = COLLISION_TYPES.convexConvex;
  8501. _COLLISION_TYPES$sphe4 = COLLISION_TYPES.sphereConvex;
  8502. _COLLISION_TYPES$plan2 = COLLISION_TYPES.planeConvex;
  8503. _COLLISION_TYPES$boxC = COLLISION_TYPES.boxConvex;
  8504. _COLLISION_TYPES$sphe5 = COLLISION_TYPES.sphereHeightfield;
  8505. _COLLISION_TYPES$boxH = COLLISION_TYPES.boxHeightfield;
  8506. _COLLISION_TYPES$conv2 = COLLISION_TYPES.convexHeightfield;
  8507. _COLLISION_TYPES$sphe6 = COLLISION_TYPES.sphereParticle;
  8508. _COLLISION_TYPES$plan3 = COLLISION_TYPES.planeParticle;
  8509. _COLLISION_TYPES$boxP = COLLISION_TYPES.boxParticle;
  8510. _COLLISION_TYPES$conv3 = COLLISION_TYPES.convexParticle;
  8511. _COLLISION_TYPES$cyli = COLLISION_TYPES.cylinderCylinder;
  8512. _COLLISION_TYPES$sphe7 = COLLISION_TYPES.sphereCylinder;
  8513. _COLLISION_TYPES$plan4 = COLLISION_TYPES.planeCylinder;
  8514. _COLLISION_TYPES$boxC2 = COLLISION_TYPES.boxCylinder;
  8515. _COLLISION_TYPES$conv4 = COLLISION_TYPES.convexCylinder;
  8516. _COLLISION_TYPES$heig = COLLISION_TYPES.heightfieldCylinder;
  8517. _COLLISION_TYPES$part = COLLISION_TYPES.particleCylinder;
  8518. _COLLISION_TYPES$sphe8 = COLLISION_TYPES.sphereTrimesh;
  8519. _COLLISION_TYPES$plan5 = COLLISION_TYPES.planeTrimesh;
  8520. /**
  8521. * Helper class for the World. Generates ContactEquations.
  8522. * @todo Sphere-ConvexPolyhedron contacts
  8523. * @todo Contact reduction
  8524. * @todo should move methods to prototype
  8525. */
  8526. class Narrowphase {
  8527. /**
  8528. * Internal storage of pooled contact points.
  8529. */
  8530. /**
  8531. * Pooled vectors.
  8532. */
  8533. get [_COLLISION_TYPES$sphe]() {
  8534. return this.sphereSphere;
  8535. }
  8536. get [_COLLISION_TYPES$sphe2]() {
  8537. return this.spherePlane;
  8538. }
  8539. get [_COLLISION_TYPES$boxB]() {
  8540. return this.boxBox;
  8541. }
  8542. get [_COLLISION_TYPES$sphe3]() {
  8543. return this.sphereBox;
  8544. }
  8545. get [_COLLISION_TYPES$plan]() {
  8546. return this.planeBox;
  8547. }
  8548. get [_COLLISION_TYPES$conv]() {
  8549. return this.convexConvex;
  8550. }
  8551. get [_COLLISION_TYPES$sphe4]() {
  8552. return this.sphereConvex;
  8553. }
  8554. get [_COLLISION_TYPES$plan2]() {
  8555. return this.planeConvex;
  8556. }
  8557. get [_COLLISION_TYPES$boxC]() {
  8558. return this.boxConvex;
  8559. }
  8560. get [_COLLISION_TYPES$sphe5]() {
  8561. return this.sphereHeightfield;
  8562. }
  8563. get [_COLLISION_TYPES$boxH]() {
  8564. return this.boxHeightfield;
  8565. }
  8566. get [_COLLISION_TYPES$conv2]() {
  8567. return this.convexHeightfield;
  8568. }
  8569. get [_COLLISION_TYPES$sphe6]() {
  8570. return this.sphereParticle;
  8571. }
  8572. get [_COLLISION_TYPES$plan3]() {
  8573. return this.planeParticle;
  8574. }
  8575. get [_COLLISION_TYPES$boxP]() {
  8576. return this.boxParticle;
  8577. }
  8578. get [_COLLISION_TYPES$conv3]() {
  8579. return this.convexParticle;
  8580. }
  8581. get [_COLLISION_TYPES$cyli]() {
  8582. return this.convexConvex;
  8583. }
  8584. get [_COLLISION_TYPES$sphe7]() {
  8585. return this.sphereConvex;
  8586. }
  8587. get [_COLLISION_TYPES$plan4]() {
  8588. return this.planeConvex;
  8589. }
  8590. get [_COLLISION_TYPES$boxC2]() {
  8591. return this.boxConvex;
  8592. }
  8593. get [_COLLISION_TYPES$conv4]() {
  8594. return this.convexConvex;
  8595. }
  8596. get [_COLLISION_TYPES$heig]() {
  8597. return this.heightfieldCylinder;
  8598. }
  8599. get [_COLLISION_TYPES$part]() {
  8600. return this.particleCylinder;
  8601. }
  8602. get [_COLLISION_TYPES$sphe8]() {
  8603. return this.sphereTrimesh;
  8604. }
  8605. get [_COLLISION_TYPES$plan5]() {
  8606. return this.planeTrimesh;
  8607. } // get [COLLISION_TYPES.convexTrimesh]() {
  8608. // return this.convexTrimesh
  8609. // }
  8610. constructor(world) {
  8611. this.contactPointPool = void 0;
  8612. this.frictionEquationPool = void 0;
  8613. this.result = void 0;
  8614. this.frictionResult = void 0;
  8615. this.v3pool = void 0;
  8616. this.world = void 0;
  8617. this.currentContactMaterial = void 0;
  8618. this.enableFrictionReduction = void 0;
  8619. this.contactPointPool = [];
  8620. this.frictionEquationPool = [];
  8621. this.result = [];
  8622. this.frictionResult = [];
  8623. this.v3pool = new Vec3Pool();
  8624. this.world = world;
  8625. this.currentContactMaterial = world.defaultContactMaterial;
  8626. this.enableFrictionReduction = false;
  8627. }
  8628. /**
  8629. * Make a contact object, by using the internal pool or creating a new one.
  8630. */
  8631. createContactEquation(bi, bj, si, sj, overrideShapeA, overrideShapeB) {
  8632. let c;
  8633. if (this.contactPointPool.length) {
  8634. c = this.contactPointPool.pop();
  8635. c.bi = bi;
  8636. c.bj = bj;
  8637. } else {
  8638. c = new ContactEquation(bi, bj);
  8639. }
  8640. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  8641. const cm = this.currentContactMaterial;
  8642. c.restitution = cm.restitution;
  8643. c.setSpookParams(cm.contactEquationStiffness, cm.contactEquationRelaxation, this.world.dt);
  8644. const matA = si.material || bi.material;
  8645. const matB = sj.material || bj.material;
  8646. if (matA && matB && matA.restitution >= 0 && matB.restitution >= 0) {
  8647. c.restitution = matA.restitution * matB.restitution;
  8648. }
  8649. c.si = overrideShapeA || si;
  8650. c.sj = overrideShapeB || sj;
  8651. return c;
  8652. }
  8653. createFrictionEquationsFromContact(contactEquation, outArray) {
  8654. const bodyA = contactEquation.bi;
  8655. const bodyB = contactEquation.bj;
  8656. const shapeA = contactEquation.si;
  8657. const shapeB = contactEquation.sj;
  8658. const world = this.world;
  8659. const cm = this.currentContactMaterial; // If friction or restitution were specified in the material, use them
  8660. let friction = cm.friction;
  8661. const matA = shapeA.material || bodyA.material;
  8662. const matB = shapeB.material || bodyB.material;
  8663. if (matA && matB && matA.friction >= 0 && matB.friction >= 0) {
  8664. friction = matA.friction * matB.friction;
  8665. }
  8666. if (friction > 0) {
  8667. // Create 2 tangent equations
  8668. const mug = friction * world.gravity.length();
  8669. let reducedMass = bodyA.invMass + bodyB.invMass;
  8670. if (reducedMass > 0) {
  8671. reducedMass = 1 / reducedMass;
  8672. }
  8673. const pool = this.frictionEquationPool;
  8674. const c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
  8675. const c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA, bodyB, mug * reducedMass);
  8676. c1.bi = c2.bi = bodyA;
  8677. c1.bj = c2.bj = bodyB;
  8678. c1.minForce = c2.minForce = -mug * reducedMass;
  8679. c1.maxForce = c2.maxForce = mug * reducedMass; // Copy over the relative vectors
  8680. c1.ri.copy(contactEquation.ri);
  8681. c1.rj.copy(contactEquation.rj);
  8682. c2.ri.copy(contactEquation.ri);
  8683. c2.rj.copy(contactEquation.rj); // Construct tangents
  8684. contactEquation.ni.tangents(c1.t, c2.t); // Set spook params
  8685. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  8686. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  8687. c1.enabled = c2.enabled = contactEquation.enabled;
  8688. outArray.push(c1, c2);
  8689. return true;
  8690. }
  8691. return false;
  8692. }
  8693. /**
  8694. * Take the average N latest contact point on the plane.
  8695. */
  8696. createFrictionFromAverage(numContacts) {
  8697. // The last contactEquation
  8698. let c = this.result[this.result.length - 1]; // Create the result: two "average" friction equations
  8699. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  8700. return;
  8701. }
  8702. const f1 = this.frictionResult[this.frictionResult.length - 2];
  8703. const f2 = this.frictionResult[this.frictionResult.length - 1];
  8704. averageNormal.setZero();
  8705. averageContactPointA.setZero();
  8706. averageContactPointB.setZero();
  8707. const bodyA = c.bi;
  8708. c.bj;
  8709. for (let i = 0; i !== numContacts; i++) {
  8710. c = this.result[this.result.length - 1 - i];
  8711. if (c.bi !== bodyA) {
  8712. averageNormal.vadd(c.ni, averageNormal);
  8713. averageContactPointA.vadd(c.ri, averageContactPointA);
  8714. averageContactPointB.vadd(c.rj, averageContactPointB);
  8715. } else {
  8716. averageNormal.vsub(c.ni, averageNormal);
  8717. averageContactPointA.vadd(c.rj, averageContactPointA);
  8718. averageContactPointB.vadd(c.ri, averageContactPointB);
  8719. }
  8720. }
  8721. const invNumContacts = 1 / numContacts;
  8722. averageContactPointA.scale(invNumContacts, f1.ri);
  8723. averageContactPointB.scale(invNumContacts, f1.rj);
  8724. f2.ri.copy(f1.ri); // Should be the same
  8725. f2.rj.copy(f1.rj);
  8726. averageNormal.normalize();
  8727. averageNormal.tangents(f1.t, f2.t); // return eq;
  8728. }
  8729. /**
  8730. * Generate all contacts between a list of body pairs
  8731. * @param p1 Array of body indices
  8732. * @param p2 Array of body indices
  8733. * @param result Array to store generated contacts
  8734. * @param oldcontacts Optional. Array of reusable contact objects
  8735. */
  8736. getContacts(p1, p2, world, result, oldcontacts, frictionResult, frictionPool) {
  8737. // Save old contact objects
  8738. this.contactPointPool = oldcontacts;
  8739. this.frictionEquationPool = frictionPool;
  8740. this.result = result;
  8741. this.frictionResult = frictionResult;
  8742. const qi = tmpQuat1;
  8743. const qj = tmpQuat2;
  8744. const xi = tmpVec1;
  8745. const xj = tmpVec2;
  8746. for (let k = 0, N = p1.length; k !== N; k++) {
  8747. // Get current collision bodies
  8748. const bi = p1[k];
  8749. const bj = p2[k]; // Get contact material
  8750. let bodyContactMaterial = null;
  8751. if (bi.material && bj.material) {
  8752. bodyContactMaterial = world.getContactMaterial(bi.material, bj.material) || null;
  8753. }
  8754. const justTest = bi.type & Body.KINEMATIC && bj.type & Body.STATIC || bi.type & Body.STATIC && bj.type & Body.KINEMATIC || bi.type & Body.KINEMATIC && bj.type & Body.KINEMATIC;
  8755. for (let i = 0; i < bi.shapes.length; i++) {
  8756. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  8757. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  8758. xi.vadd(bi.position, xi);
  8759. const si = bi.shapes[i];
  8760. for (let j = 0; j < bj.shapes.length; j++) {
  8761. // Compute world transform of shapes
  8762. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  8763. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  8764. xj.vadd(bj.position, xj);
  8765. const sj = bj.shapes[j];
  8766. if (!(si.collisionFilterMask & sj.collisionFilterGroup && sj.collisionFilterMask & si.collisionFilterGroup)) {
  8767. continue;
  8768. }
  8769. if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
  8770. continue;
  8771. } // Get collision material
  8772. let shapeContactMaterial = null;
  8773. if (si.material && sj.material) {
  8774. shapeContactMaterial = world.getContactMaterial(si.material, sj.material) || null;
  8775. }
  8776. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial; // Get contacts
  8777. const resolverIndex = si.type | sj.type;
  8778. const resolver = this[resolverIndex];
  8779. if (resolver) {
  8780. let retval = false; // TO DO: investigate why sphereParticle and convexParticle
  8781. // resolvers expect si and sj shapes to be in reverse order
  8782. // (i.e. larger integer value type first instead of smaller first)
  8783. if (si.type < sj.type) {
  8784. retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8785. } else {
  8786. retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);
  8787. }
  8788. if (retval && justTest) {
  8789. // Register overlap
  8790. world.shapeOverlapKeeper.set(si.id, sj.id);
  8791. world.bodyOverlapKeeper.set(bi.id, bj.id);
  8792. }
  8793. }
  8794. }
  8795. }
  8796. }
  8797. }
  8798. sphereSphere(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8799. if (justTest) {
  8800. return xi.distanceSquared(xj) < (si.radius + sj.radius) ** 2;
  8801. } // We will have only one contact in this case
  8802. const contactEq = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal
  8803. xj.vsub(xi, contactEq.ni);
  8804. contactEq.ni.normalize(); // Contact point locations
  8805. contactEq.ri.copy(contactEq.ni);
  8806. contactEq.rj.copy(contactEq.ni);
  8807. contactEq.ri.scale(si.radius, contactEq.ri);
  8808. contactEq.rj.scale(-sj.radius, contactEq.rj);
  8809. contactEq.ri.vadd(xi, contactEq.ri);
  8810. contactEq.ri.vsub(bi.position, contactEq.ri);
  8811. contactEq.rj.vadd(xj, contactEq.rj);
  8812. contactEq.rj.vsub(bj.position, contactEq.rj);
  8813. this.result.push(contactEq);
  8814. this.createFrictionEquationsFromContact(contactEq, this.frictionResult);
  8815. }
  8816. spherePlane(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8817. // We will have one contact in this case
  8818. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj); // Contact normal
  8819. r.ni.set(0, 0, 1);
  8820. qj.vmult(r.ni, r.ni);
  8821. r.ni.negate(r.ni); // body i is the sphere, flip normal
  8822. r.ni.normalize(); // Needed?
  8823. // Vector from sphere center to contact point
  8824. r.ni.scale(si.radius, r.ri); // Project down sphere on plane
  8825. xi.vsub(xj, point_on_plane_to_sphere);
  8826. r.ni.scale(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  8827. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, r.rj); // The sphere position projected to plane
  8828. if (-point_on_plane_to_sphere.dot(r.ni) <= si.radius) {
  8829. if (justTest) {
  8830. return true;
  8831. } // Make it relative to the body
  8832. const ri = r.ri;
  8833. const rj = r.rj;
  8834. ri.vadd(xi, ri);
  8835. ri.vsub(bi.position, ri);
  8836. rj.vadd(xj, rj);
  8837. rj.vsub(bj.position, rj);
  8838. this.result.push(r);
  8839. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8840. }
  8841. }
  8842. boxBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8843. si.convexPolyhedronRepresentation.material = si.material;
  8844. sj.convexPolyhedronRepresentation.material = sj.material;
  8845. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  8846. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  8847. return this.convexConvex(si.convexPolyhedronRepresentation, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  8848. }
  8849. sphereBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  8850. const v3pool = this.v3pool; // we refer to the box as body j
  8851. const sides = sphereBox_sides;
  8852. xi.vsub(xj, box_to_sphere);
  8853. sj.getSideNormals(sides, qj);
  8854. const R = si.radius;
  8855. let found = false; // Store the resulting side penetration info
  8856. const side_ns = sphereBox_side_ns;
  8857. const side_ns1 = sphereBox_side_ns1;
  8858. const side_ns2 = sphereBox_side_ns2;
  8859. let side_h = null;
  8860. let side_penetrations = 0;
  8861. let side_dot1 = 0;
  8862. let side_dot2 = 0;
  8863. let side_distance = null;
  8864. for (let idx = 0, nsides = sides.length; idx !== nsides && found === false; idx++) {
  8865. // Get the plane side normal (ns)
  8866. const ns = sphereBox_ns;
  8867. ns.copy(sides[idx]);
  8868. const h = ns.length();
  8869. ns.normalize(); // The normal/distance dot product tells which side of the plane we are
  8870. const dot = box_to_sphere.dot(ns);
  8871. if (dot < h + R && dot > 0) {
  8872. // Intersects plane. Now check the other two dimensions
  8873. const ns1 = sphereBox_ns1;
  8874. const ns2 = sphereBox_ns2;
  8875. ns1.copy(sides[(idx + 1) % 3]);
  8876. ns2.copy(sides[(idx + 2) % 3]);
  8877. const h1 = ns1.length();
  8878. const h2 = ns2.length();
  8879. ns1.normalize();
  8880. ns2.normalize();
  8881. const dot1 = box_to_sphere.dot(ns1);
  8882. const dot2 = box_to_sphere.dot(ns2);
  8883. if (dot1 < h1 && dot1 > -h1 && dot2 < h2 && dot2 > -h2) {
  8884. const dist = Math.abs(dot - h - R);
  8885. if (side_distance === null || dist < side_distance) {
  8886. side_distance = dist;
  8887. side_dot1 = dot1;
  8888. side_dot2 = dot2;
  8889. side_h = h;
  8890. side_ns.copy(ns);
  8891. side_ns1.copy(ns1);
  8892. side_ns2.copy(ns2);
  8893. side_penetrations++;
  8894. if (justTest) {
  8895. return true;
  8896. }
  8897. }
  8898. }
  8899. }
  8900. }
  8901. if (side_penetrations) {
  8902. found = true;
  8903. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8904. side_ns.scale(-R, r.ri); // Sphere r
  8905. r.ni.copy(side_ns);
  8906. r.ni.negate(r.ni); // Normal should be out of sphere
  8907. side_ns.scale(side_h, side_ns);
  8908. side_ns1.scale(side_dot1, side_ns1);
  8909. side_ns.vadd(side_ns1, side_ns);
  8910. side_ns2.scale(side_dot2, side_ns2);
  8911. side_ns.vadd(side_ns2, r.rj); // Make relative to bodies
  8912. r.ri.vadd(xi, r.ri);
  8913. r.ri.vsub(bi.position, r.ri);
  8914. r.rj.vadd(xj, r.rj);
  8915. r.rj.vsub(bj.position, r.rj);
  8916. this.result.push(r);
  8917. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8918. } // Check corners
  8919. let rj = v3pool.get();
  8920. const sphere_to_corner = sphereBox_sphere_to_corner;
  8921. for (let j = 0; j !== 2 && !found; j++) {
  8922. for (let k = 0; k !== 2 && !found; k++) {
  8923. for (let l = 0; l !== 2 && !found; l++) {
  8924. rj.set(0, 0, 0);
  8925. if (j) {
  8926. rj.vadd(sides[0], rj);
  8927. } else {
  8928. rj.vsub(sides[0], rj);
  8929. }
  8930. if (k) {
  8931. rj.vadd(sides[1], rj);
  8932. } else {
  8933. rj.vsub(sides[1], rj);
  8934. }
  8935. if (l) {
  8936. rj.vadd(sides[2], rj);
  8937. } else {
  8938. rj.vsub(sides[2], rj);
  8939. } // World position of corner
  8940. xj.vadd(rj, sphere_to_corner);
  8941. sphere_to_corner.vsub(xi, sphere_to_corner);
  8942. if (sphere_to_corner.lengthSquared() < R * R) {
  8943. if (justTest) {
  8944. return true;
  8945. }
  8946. found = true;
  8947. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  8948. r.ri.copy(sphere_to_corner);
  8949. r.ri.normalize();
  8950. r.ni.copy(r.ri);
  8951. r.ri.scale(R, r.ri);
  8952. r.rj.copy(rj); // Make relative to bodies
  8953. r.ri.vadd(xi, r.ri);
  8954. r.ri.vsub(bi.position, r.ri);
  8955. r.rj.vadd(xj, r.rj);
  8956. r.rj.vsub(bj.position, r.rj);
  8957. this.result.push(r);
  8958. this.createFrictionEquationsFromContact(r, this.frictionResult);
  8959. }
  8960. }
  8961. }
  8962. }
  8963. v3pool.release(rj);
  8964. rj = null; // Check edges
  8965. const edgeTangent = v3pool.get();
  8966. const edgeCenter = v3pool.get();
  8967. const r = v3pool.get(); // r = edge center to sphere center
  8968. const orthogonal = v3pool.get();
  8969. const dist = v3pool.get();
  8970. const Nsides = sides.length;
  8971. for (let j = 0; j !== Nsides && !found; j++) {
  8972. for (let k = 0; k !== Nsides && !found; k++) {
  8973. if (j % 3 !== k % 3) {
  8974. // Get edge tangent
  8975. sides[k].cross(sides[j], edgeTangent);
  8976. edgeTangent.normalize();
  8977. sides[j].vadd(sides[k], edgeCenter);
  8978. r.copy(xi);
  8979. r.vsub(edgeCenter, r);
  8980. r.vsub(xj, r);
  8981. const orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  8982. edgeTangent.scale(orthonorm, orthogonal); // Vector from edge center to sphere center in the tangent direction
  8983. // Find the third side orthogonal to this one
  8984. let l = 0;
  8985. while (l === j % 3 || l === k % 3) {
  8986. l++;
  8987. } // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  8988. dist.copy(xi);
  8989. dist.vsub(orthogonal, dist);
  8990. dist.vsub(edgeCenter, dist);
  8991. dist.vsub(xj, dist); // Distances in tangent direction and distance in the plane orthogonal to it
  8992. const tdist = Math.abs(orthonorm);
  8993. const ndist = dist.length();
  8994. if (tdist < sides[l].length() && ndist < R) {
  8995. if (justTest) {
  8996. return true;
  8997. }
  8998. found = true;
  8999. const res = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9000. edgeCenter.vadd(orthogonal, res.rj); // box rj
  9001. res.rj.copy(res.rj);
  9002. dist.negate(res.ni);
  9003. res.ni.normalize();
  9004. res.ri.copy(res.rj);
  9005. res.ri.vadd(xj, res.ri);
  9006. res.ri.vsub(xi, res.ri);
  9007. res.ri.normalize();
  9008. res.ri.scale(R, res.ri); // Make relative to bodies
  9009. res.ri.vadd(xi, res.ri);
  9010. res.ri.vsub(bi.position, res.ri);
  9011. res.rj.vadd(xj, res.rj);
  9012. res.rj.vsub(bj.position, res.rj);
  9013. this.result.push(res);
  9014. this.createFrictionEquationsFromContact(res, this.frictionResult);
  9015. }
  9016. }
  9017. }
  9018. }
  9019. v3pool.release(edgeTangent, edgeCenter, r, orthogonal, dist);
  9020. }
  9021. planeBox(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9022. sj.convexPolyhedronRepresentation.material = sj.material;
  9023. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  9024. sj.convexPolyhedronRepresentation.id = sj.id;
  9025. return this.planeConvex(si, sj.convexPolyhedronRepresentation, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9026. }
  9027. convexConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest, faceListA, faceListB) {
  9028. const sepAxis = convexConvex_sepAxis;
  9029. if (xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius) {
  9030. return;
  9031. }
  9032. if (si.findSeparatingAxis(sj, xi, qi, xj, qj, sepAxis, faceListA, faceListB)) {
  9033. const res = [];
  9034. const q = convexConvex_q;
  9035. si.clipAgainstHull(xi, qi, sj, xj, qj, sepAxis, -100, 100, res);
  9036. let numContacts = 0;
  9037. for (let j = 0; j !== res.length; j++) {
  9038. if (justTest) {
  9039. return true;
  9040. }
  9041. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9042. const ri = r.ri;
  9043. const rj = r.rj;
  9044. sepAxis.negate(r.ni);
  9045. res[j].normal.negate(q);
  9046. q.scale(res[j].depth, q);
  9047. res[j].point.vadd(q, ri);
  9048. rj.copy(res[j].point); // Contact points are in world coordinates. Transform back to relative
  9049. ri.vsub(xi, ri);
  9050. rj.vsub(xj, rj); // Make relative to bodies
  9051. ri.vadd(xi, ri);
  9052. ri.vsub(bi.position, ri);
  9053. rj.vadd(xj, rj);
  9054. rj.vsub(bj.position, rj);
  9055. this.result.push(r);
  9056. numContacts++;
  9057. if (!this.enableFrictionReduction) {
  9058. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9059. }
  9060. }
  9061. if (this.enableFrictionReduction && numContacts) {
  9062. this.createFrictionFromAverage(numContacts);
  9063. }
  9064. }
  9065. }
  9066. sphereConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9067. const v3pool = this.v3pool;
  9068. xi.vsub(xj, convex_to_sphere);
  9069. const normals = sj.faceNormals;
  9070. const faces = sj.faces;
  9071. const verts = sj.vertices;
  9072. const R = si.radius;
  9073. // return;
  9074. // }
  9075. let found = false; // Check corners
  9076. for (let i = 0; i !== verts.length; i++) {
  9077. const v = verts[i]; // World position of corner
  9078. const worldCorner = sphereConvex_worldCorner;
  9079. qj.vmult(v, worldCorner);
  9080. xj.vadd(worldCorner, worldCorner);
  9081. const sphere_to_corner = sphereConvex_sphereToCorner;
  9082. worldCorner.vsub(xi, sphere_to_corner);
  9083. if (sphere_to_corner.lengthSquared() < R * R) {
  9084. if (justTest) {
  9085. return true;
  9086. }
  9087. found = true;
  9088. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9089. r.ri.copy(sphere_to_corner);
  9090. r.ri.normalize();
  9091. r.ni.copy(r.ri);
  9092. r.ri.scale(R, r.ri);
  9093. worldCorner.vsub(xj, r.rj); // Should be relative to the body.
  9094. r.ri.vadd(xi, r.ri);
  9095. r.ri.vsub(bi.position, r.ri); // Should be relative to the body.
  9096. r.rj.vadd(xj, r.rj);
  9097. r.rj.vsub(bj.position, r.rj);
  9098. this.result.push(r);
  9099. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9100. return;
  9101. }
  9102. } // Check side (plane) intersections
  9103. for (let i = 0, nfaces = faces.length; i !== nfaces && found === false; i++) {
  9104. const normal = normals[i];
  9105. const face = faces[i]; // Get world-transformed normal of the face
  9106. const worldNormal = sphereConvex_worldNormal;
  9107. qj.vmult(normal, worldNormal); // Get a world vertex from the face
  9108. const worldPoint = sphereConvex_worldPoint;
  9109. qj.vmult(verts[face[0]], worldPoint);
  9110. worldPoint.vadd(xj, worldPoint); // Get a point on the sphere, closest to the face normal
  9111. const worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  9112. worldNormal.scale(-R, worldSpherePointClosestToPlane);
  9113. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane); // Vector from a face point to the closest point on the sphere
  9114. const penetrationVec = sphereConvex_penetrationVec;
  9115. worldSpherePointClosestToPlane.vsub(worldPoint, penetrationVec); // The penetration. Negative value means overlap.
  9116. const penetration = penetrationVec.dot(worldNormal);
  9117. const worldPointToSphere = sphereConvex_sphereToWorldPoint;
  9118. xi.vsub(worldPoint, worldPointToSphere);
  9119. if (penetration < 0 && worldPointToSphere.dot(worldNormal) > 0) {
  9120. // Intersects plane. Now check if the sphere is inside the face polygon
  9121. const faceVerts = []; // Face vertices, in world coords
  9122. for (let j = 0, Nverts = face.length; j !== Nverts; j++) {
  9123. const worldVertex = v3pool.get();
  9124. qj.vmult(verts[face[j]], worldVertex);
  9125. xj.vadd(worldVertex, worldVertex);
  9126. faceVerts.push(worldVertex);
  9127. }
  9128. if (pointInPolygon(faceVerts, worldNormal, xi)) {
  9129. // Is the sphere center in the face polygon?
  9130. if (justTest) {
  9131. return true;
  9132. }
  9133. found = true;
  9134. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9135. worldNormal.scale(-R, r.ri); // Contact offset, from sphere center to contact
  9136. worldNormal.negate(r.ni); // Normal pointing out of sphere
  9137. const penetrationVec2 = v3pool.get();
  9138. worldNormal.scale(-penetration, penetrationVec2);
  9139. const penetrationSpherePoint = v3pool.get();
  9140. worldNormal.scale(-R, penetrationSpherePoint); //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  9141. xi.vsub(xj, r.rj);
  9142. r.rj.vadd(penetrationSpherePoint, r.rj);
  9143. r.rj.vadd(penetrationVec2, r.rj); // Should be relative to the body.
  9144. r.rj.vadd(xj, r.rj);
  9145. r.rj.vsub(bj.position, r.rj); // Should be relative to the body.
  9146. r.ri.vadd(xi, r.ri);
  9147. r.ri.vsub(bi.position, r.ri);
  9148. v3pool.release(penetrationVec2);
  9149. v3pool.release(penetrationSpherePoint);
  9150. this.result.push(r);
  9151. this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices
  9152. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9153. v3pool.release(faceVerts[j]);
  9154. }
  9155. return; // We only expect *one* face contact
  9156. } else {
  9157. // Edge?
  9158. for (let j = 0; j !== face.length; j++) {
  9159. // Get two world transformed vertices
  9160. const v1 = v3pool.get();
  9161. const v2 = v3pool.get();
  9162. qj.vmult(verts[face[(j + 1) % face.length]], v1);
  9163. qj.vmult(verts[face[(j + 2) % face.length]], v2);
  9164. xj.vadd(v1, v1);
  9165. xj.vadd(v2, v2); // Construct edge vector
  9166. const edge = sphereConvex_edge;
  9167. v2.vsub(v1, edge); // Construct the same vector, but normalized
  9168. const edgeUnit = sphereConvex_edgeUnit;
  9169. edge.unit(edgeUnit); // p is xi projected onto the edge
  9170. const p = v3pool.get();
  9171. const v1_to_xi = v3pool.get();
  9172. xi.vsub(v1, v1_to_xi);
  9173. const dot = v1_to_xi.dot(edgeUnit);
  9174. edgeUnit.scale(dot, p);
  9175. p.vadd(v1, p); // Compute a vector from p to the center of the sphere
  9176. const xi_to_p = v3pool.get();
  9177. p.vsub(xi, xi_to_p); // Collision if the edge-sphere distance is less than the radius
  9178. // AND if p is in between v1 and v2
  9179. if (dot > 0 && dot * dot < edge.lengthSquared() && xi_to_p.lengthSquared() < R * R) {
  9180. // Collision if the edge-sphere distance is less than the radius
  9181. // Edge contact!
  9182. if (justTest) {
  9183. return true;
  9184. }
  9185. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9186. p.vsub(xj, r.rj);
  9187. p.vsub(xi, r.ni);
  9188. r.ni.normalize();
  9189. r.ni.scale(R, r.ri); // Should be relative to the body.
  9190. r.rj.vadd(xj, r.rj);
  9191. r.rj.vsub(bj.position, r.rj); // Should be relative to the body.
  9192. r.ri.vadd(xi, r.ri);
  9193. r.ri.vsub(bi.position, r.ri);
  9194. this.result.push(r);
  9195. this.createFrictionEquationsFromContact(r, this.frictionResult); // Release world vertices
  9196. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9197. v3pool.release(faceVerts[j]);
  9198. }
  9199. v3pool.release(v1);
  9200. v3pool.release(v2);
  9201. v3pool.release(p);
  9202. v3pool.release(xi_to_p);
  9203. v3pool.release(v1_to_xi);
  9204. return;
  9205. }
  9206. v3pool.release(v1);
  9207. v3pool.release(v2);
  9208. v3pool.release(p);
  9209. v3pool.release(xi_to_p);
  9210. v3pool.release(v1_to_xi);
  9211. }
  9212. } // Release world vertices
  9213. for (let j = 0, Nfaceverts = faceVerts.length; j !== Nfaceverts; j++) {
  9214. v3pool.release(faceVerts[j]);
  9215. }
  9216. }
  9217. }
  9218. }
  9219. planeConvex(planeShape, convexShape, planePosition, convexPosition, planeQuat, convexQuat, planeBody, convexBody, si, sj, justTest) {
  9220. // Simply return the points behind the plane.
  9221. const worldVertex = planeConvex_v;
  9222. const worldNormal = planeConvex_normal;
  9223. worldNormal.set(0, 0, 1);
  9224. planeQuat.vmult(worldNormal, worldNormal); // Turn normal according to plane orientation
  9225. let numContacts = 0;
  9226. const relpos = planeConvex_relpos;
  9227. for (let i = 0; i !== convexShape.vertices.length; i++) {
  9228. // Get world convex vertex
  9229. worldVertex.copy(convexShape.vertices[i]);
  9230. convexQuat.vmult(worldVertex, worldVertex);
  9231. convexPosition.vadd(worldVertex, worldVertex);
  9232. worldVertex.vsub(planePosition, relpos);
  9233. const dot = worldNormal.dot(relpos);
  9234. if (dot <= 0.0) {
  9235. if (justTest) {
  9236. return true;
  9237. }
  9238. const r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj); // Get vertex position projected on plane
  9239. const projected = planeConvex_projected;
  9240. worldNormal.scale(worldNormal.dot(relpos), projected);
  9241. worldVertex.vsub(projected, projected);
  9242. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  9243. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  9244. // rj is now just the vector from the convex center to the vertex
  9245. worldVertex.vsub(convexPosition, r.rj); // Make it relative to the body
  9246. r.ri.vadd(planePosition, r.ri);
  9247. r.ri.vsub(planeBody.position, r.ri);
  9248. r.rj.vadd(convexPosition, r.rj);
  9249. r.rj.vsub(convexBody.position, r.rj);
  9250. this.result.push(r);
  9251. numContacts++;
  9252. if (!this.enableFrictionReduction) {
  9253. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9254. }
  9255. }
  9256. }
  9257. if (this.enableFrictionReduction && numContacts) {
  9258. this.createFrictionFromAverage(numContacts);
  9259. }
  9260. }
  9261. boxConvex(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9262. si.convexPolyhedronRepresentation.material = si.material;
  9263. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9264. return this.convexConvex(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9265. }
  9266. sphereHeightfield(sphereShape, hfShape, spherePos, hfPos, sphereQuat, hfQuat, sphereBody, hfBody, rsi, rsj, justTest) {
  9267. const data = hfShape.data;
  9268. const radius = sphereShape.radius;
  9269. const w = hfShape.elementSize;
  9270. const worldPillarOffset = sphereHeightfield_tmp2; // Get sphere position to heightfield local!
  9271. const localSpherePos = sphereHeightfield_tmp1;
  9272. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos); // Get the index of the data points to test against
  9273. let iMinX = Math.floor((localSpherePos.x - radius) / w) - 1;
  9274. let iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1;
  9275. let iMinY = Math.floor((localSpherePos.y - radius) / w) - 1;
  9276. let iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1; // Bail out if we are out of the terrain
  9277. if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
  9278. return;
  9279. } // Clamp index to edges
  9280. if (iMinX < 0) {
  9281. iMinX = 0;
  9282. }
  9283. if (iMaxX < 0) {
  9284. iMaxX = 0;
  9285. }
  9286. if (iMinY < 0) {
  9287. iMinY = 0;
  9288. }
  9289. if (iMaxY < 0) {
  9290. iMaxY = 0;
  9291. }
  9292. if (iMinX >= data.length) {
  9293. iMinX = data.length - 1;
  9294. }
  9295. if (iMaxX >= data.length) {
  9296. iMaxX = data.length - 1;
  9297. }
  9298. if (iMaxY >= data[0].length) {
  9299. iMaxY = data[0].length - 1;
  9300. }
  9301. if (iMinY >= data[0].length) {
  9302. iMinY = data[0].length - 1;
  9303. }
  9304. const minMax = [];
  9305. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  9306. const min = minMax[0];
  9307. const max = minMax[1]; // Bail out if we can't touch the bounding height box
  9308. if (localSpherePos.z - radius > max || localSpherePos.z + radius < min) {
  9309. return;
  9310. }
  9311. const result = this.result;
  9312. for (let i = iMinX; i < iMaxX; i++) {
  9313. for (let j = iMinY; j < iMaxY; j++) {
  9314. const numContactsBefore = result.length;
  9315. let intersecting = false; // Lower triangle
  9316. hfShape.getConvexTrianglePillar(i, j, false);
  9317. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9318. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  9319. intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
  9320. }
  9321. if (justTest && intersecting) {
  9322. return true;
  9323. } // Upper triangle
  9324. hfShape.getConvexTrianglePillar(i, j, true);
  9325. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9326. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  9327. intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
  9328. }
  9329. if (justTest && intersecting) {
  9330. return true;
  9331. }
  9332. const numContacts = result.length - numContactsBefore;
  9333. if (numContacts > 2) {
  9334. return;
  9335. }
  9336. /*
  9337. // Skip all but 1
  9338. for (let k = 0; k < numContacts - 1; k++) {
  9339. result.pop();
  9340. }
  9341. */
  9342. }
  9343. }
  9344. }
  9345. boxHeightfield(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9346. si.convexPolyhedronRepresentation.material = si.material;
  9347. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9348. return this.convexHeightfield(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9349. }
  9350. convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest) {
  9351. const data = hfShape.data;
  9352. const w = hfShape.elementSize;
  9353. const radius = convexShape.boundingSphereRadius;
  9354. const worldPillarOffset = convexHeightfield_tmp2;
  9355. const faceList = convexHeightfield_faceList; // Get sphere position to heightfield local!
  9356. const localConvexPos = convexHeightfield_tmp1;
  9357. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos); // Get the index of the data points to test against
  9358. let iMinX = Math.floor((localConvexPos.x - radius) / w) - 1;
  9359. let iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1;
  9360. let iMinY = Math.floor((localConvexPos.y - radius) / w) - 1;
  9361. let iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1; // Bail out if we are out of the terrain
  9362. if (iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length) {
  9363. return;
  9364. } // Clamp index to edges
  9365. if (iMinX < 0) {
  9366. iMinX = 0;
  9367. }
  9368. if (iMaxX < 0) {
  9369. iMaxX = 0;
  9370. }
  9371. if (iMinY < 0) {
  9372. iMinY = 0;
  9373. }
  9374. if (iMaxY < 0) {
  9375. iMaxY = 0;
  9376. }
  9377. if (iMinX >= data.length) {
  9378. iMinX = data.length - 1;
  9379. }
  9380. if (iMaxX >= data.length) {
  9381. iMaxX = data.length - 1;
  9382. }
  9383. if (iMaxY >= data[0].length) {
  9384. iMaxY = data[0].length - 1;
  9385. }
  9386. if (iMinY >= data[0].length) {
  9387. iMinY = data[0].length - 1;
  9388. }
  9389. const minMax = [];
  9390. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  9391. const min = minMax[0];
  9392. const max = minMax[1]; // Bail out if we're cant touch the bounding height box
  9393. if (localConvexPos.z - radius > max || localConvexPos.z + radius < min) {
  9394. return;
  9395. }
  9396. for (let i = iMinX; i < iMaxX; i++) {
  9397. for (let j = iMinY; j < iMaxY; j++) {
  9398. let intersecting = false; // Lower triangle
  9399. hfShape.getConvexTrianglePillar(i, j, false);
  9400. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9401. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  9402. intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
  9403. }
  9404. if (justTest && intersecting) {
  9405. return true;
  9406. } // Upper triangle
  9407. hfShape.getConvexTrianglePillar(i, j, true);
  9408. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  9409. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  9410. intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, justTest, faceList, null);
  9411. }
  9412. if (justTest && intersecting) {
  9413. return true;
  9414. }
  9415. }
  9416. }
  9417. }
  9418. sphereParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9419. // The normal is the unit vector from sphere center to particle center
  9420. const normal = particleSphere_normal;
  9421. normal.set(0, 0, 1);
  9422. xi.vsub(xj, normal);
  9423. const lengthSquared = normal.lengthSquared();
  9424. if (lengthSquared <= sj.radius * sj.radius) {
  9425. if (justTest) {
  9426. return true;
  9427. }
  9428. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9429. normal.normalize();
  9430. r.rj.copy(normal);
  9431. r.rj.scale(sj.radius, r.rj);
  9432. r.ni.copy(normal); // Contact normal
  9433. r.ni.negate(r.ni);
  9434. r.ri.set(0, 0, 0); // Center of particle
  9435. this.result.push(r);
  9436. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9437. }
  9438. }
  9439. planeParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9440. const normal = particlePlane_normal;
  9441. normal.set(0, 0, 1);
  9442. bj.quaternion.vmult(normal, normal); // Turn normal according to plane orientation
  9443. const relpos = particlePlane_relpos;
  9444. xi.vsub(bj.position, relpos);
  9445. const dot = normal.dot(relpos);
  9446. if (dot <= 0.0) {
  9447. if (justTest) {
  9448. return true;
  9449. }
  9450. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9451. r.ni.copy(normal); // Contact normal is the plane normal
  9452. r.ni.negate(r.ni);
  9453. r.ri.set(0, 0, 0); // Center of particle
  9454. // Get particle position projected on plane
  9455. const projected = particlePlane_projected;
  9456. normal.scale(normal.dot(xi), projected);
  9457. xi.vsub(projected, projected); //projected.vadd(bj.position,projected);
  9458. // rj is now the projected world position minus plane position
  9459. r.rj.copy(projected);
  9460. this.result.push(r);
  9461. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9462. }
  9463. }
  9464. boxParticle(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9465. si.convexPolyhedronRepresentation.material = si.material;
  9466. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  9467. return this.convexParticle(si.convexPolyhedronRepresentation, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
  9468. }
  9469. convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest) {
  9470. let penetratedFaceIndex = -1;
  9471. const penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  9472. const worldPenetrationVec = convexParticle_worldPenetrationVec;
  9473. let minPenetration = null;
  9474. const local = convexParticle_local;
  9475. local.copy(xi);
  9476. local.vsub(xj, local); // Convert position to relative the convex origin
  9477. qj.conjugate(cqj);
  9478. cqj.vmult(local, local);
  9479. if (sj.pointIsInside(local)) {
  9480. if (sj.worldVerticesNeedsUpdate) {
  9481. sj.computeWorldVertices(xj, qj);
  9482. }
  9483. if (sj.worldFaceNormalsNeedsUpdate) {
  9484. sj.computeWorldFaceNormals(qj);
  9485. } // For each world polygon in the polyhedra
  9486. for (let i = 0, nfaces = sj.faces.length; i !== nfaces; i++) {
  9487. // Construct world face vertices
  9488. const verts = [sj.worldVertices[sj.faces[i][0]]];
  9489. const normal = sj.worldFaceNormals[i]; // Check how much the particle penetrates the polygon plane.
  9490. xi.vsub(verts[0], convexParticle_vertexToParticle);
  9491. const penetration = -normal.dot(convexParticle_vertexToParticle);
  9492. if (minPenetration === null || Math.abs(penetration) < Math.abs(minPenetration)) {
  9493. if (justTest) {
  9494. return true;
  9495. }
  9496. minPenetration = penetration;
  9497. penetratedFaceIndex = i;
  9498. penetratedFaceNormal.copy(normal);
  9499. }
  9500. }
  9501. if (penetratedFaceIndex !== -1) {
  9502. // Setup contact
  9503. const r = this.createContactEquation(bi, bj, si, sj, rsi, rsj);
  9504. penetratedFaceNormal.scale(minPenetration, worldPenetrationVec); // rj is the particle position projected to the face
  9505. worldPenetrationVec.vadd(xi, worldPenetrationVec);
  9506. worldPenetrationVec.vsub(xj, worldPenetrationVec);
  9507. r.rj.copy(worldPenetrationVec); //const projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  9508. //projectedToFace.copy(r.rj);
  9509. //qj.vmult(r.rj,r.rj);
  9510. penetratedFaceNormal.negate(r.ni); // Contact normal
  9511. r.ri.set(0, 0, 0); // Center of particle
  9512. const ri = r.ri;
  9513. const rj = r.rj; // Make relative to bodies
  9514. ri.vadd(xi, ri);
  9515. ri.vsub(bi.position, ri);
  9516. rj.vadd(xj, rj);
  9517. rj.vsub(bj.position, rj);
  9518. this.result.push(r);
  9519. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9520. } else {
  9521. console.warn('Point found inside convex, but did not find penetrating face!');
  9522. }
  9523. }
  9524. }
  9525. heightfieldCylinder(hfShape, convexShape, hfPos, convexPos, hfQuat, convexQuat, hfBody, convexBody, rsi, rsj, justTest) {
  9526. return this.convexHeightfield(convexShape, hfShape, convexPos, hfPos, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest);
  9527. }
  9528. particleCylinder(si, sj, xi, xj, qi, qj, bi, bj, rsi, rsj, justTest) {
  9529. return this.convexParticle(sj, si, xj, xi, qj, qi, bj, bi, rsi, rsj, justTest);
  9530. }
  9531. sphereTrimesh(sphereShape, trimeshShape, spherePos, trimeshPos, sphereQuat, trimeshQuat, sphereBody, trimeshBody, rsi, rsj, justTest) {
  9532. const edgeVertexA = sphereTrimesh_edgeVertexA;
  9533. const edgeVertexB = sphereTrimesh_edgeVertexB;
  9534. const edgeVector = sphereTrimesh_edgeVector;
  9535. const edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  9536. const localSpherePos = sphereTrimesh_localSpherePos;
  9537. const tmp = sphereTrimesh_tmp;
  9538. const localSphereAABB = sphereTrimesh_localSphereAABB;
  9539. const v2 = sphereTrimesh_v2;
  9540. const relpos = sphereTrimesh_relpos;
  9541. const triangles = sphereTrimesh_triangles; // Convert sphere position to local in the trimesh
  9542. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos); // Get the aabb of the sphere locally in the trimesh
  9543. const sphereRadius = sphereShape.radius;
  9544. localSphereAABB.lowerBound.set(localSpherePos.x - sphereRadius, localSpherePos.y - sphereRadius, localSpherePos.z - sphereRadius);
  9545. localSphereAABB.upperBound.set(localSpherePos.x + sphereRadius, localSpherePos.y + sphereRadius, localSpherePos.z + sphereRadius);
  9546. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles); //for (let i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  9547. // Vertices
  9548. const v = sphereTrimesh_v;
  9549. const radiusSquared = sphereShape.radius * sphereShape.radius;
  9550. for (let i = 0; i < triangles.length; i++) {
  9551. for (let j = 0; j < 3; j++) {
  9552. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v); // Check vertex overlap in sphere
  9553. v.vsub(localSpherePos, relpos);
  9554. if (relpos.lengthSquared() <= radiusSquared) {
  9555. // Safe up
  9556. v2.copy(v);
  9557. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  9558. v.vsub(spherePos, relpos);
  9559. if (justTest) {
  9560. return true;
  9561. }
  9562. let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9563. r.ni.copy(relpos);
  9564. r.ni.normalize(); // ri is the vector from sphere center to the sphere surface
  9565. r.ri.copy(r.ni);
  9566. r.ri.scale(sphereShape.radius, r.ri);
  9567. r.ri.vadd(spherePos, r.ri);
  9568. r.ri.vsub(sphereBody.position, r.ri);
  9569. r.rj.copy(v);
  9570. r.rj.vsub(trimeshBody.position, r.rj); // Store result
  9571. this.result.push(r);
  9572. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9573. }
  9574. }
  9575. } // Check all edges
  9576. for (let i = 0; i < triangles.length; i++) {
  9577. for (let j = 0; j < 3; j++) {
  9578. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  9579. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + (j + 1) % 3], edgeVertexB);
  9580. edgeVertexB.vsub(edgeVertexA, edgeVector); // Project sphere position to the edge
  9581. localSpherePos.vsub(edgeVertexB, tmp);
  9582. const positionAlongEdgeB = tmp.dot(edgeVector);
  9583. localSpherePos.vsub(edgeVertexA, tmp);
  9584. let positionAlongEdgeA = tmp.dot(edgeVector);
  9585. if (positionAlongEdgeA > 0 && positionAlongEdgeB < 0) {
  9586. // Now check the orthogonal distance from edge to sphere center
  9587. localSpherePos.vsub(edgeVertexA, tmp);
  9588. edgeVectorUnit.copy(edgeVector);
  9589. edgeVectorUnit.normalize();
  9590. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  9591. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  9592. tmp.vadd(edgeVertexA, tmp); // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  9593. const dist = tmp.distanceTo(localSpherePos);
  9594. if (dist < sphereShape.radius) {
  9595. if (justTest) {
  9596. return true;
  9597. }
  9598. const r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9599. tmp.vsub(localSpherePos, r.ni);
  9600. r.ni.normalize();
  9601. r.ni.scale(sphereShape.radius, r.ri);
  9602. r.ri.vadd(spherePos, r.ri);
  9603. r.ri.vsub(sphereBody.position, r.ri);
  9604. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  9605. tmp.vsub(trimeshBody.position, r.rj);
  9606. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  9607. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  9608. this.result.push(r);
  9609. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9610. }
  9611. }
  9612. }
  9613. } // Triangle faces
  9614. const va = sphereTrimesh_va;
  9615. const vb = sphereTrimesh_vb;
  9616. const vc = sphereTrimesh_vc;
  9617. const normal = sphereTrimesh_normal;
  9618. for (let i = 0, N = triangles.length; i !== N; i++) {
  9619. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  9620. trimeshShape.getNormal(triangles[i], normal);
  9621. localSpherePos.vsub(va, tmp);
  9622. let dist = tmp.dot(normal);
  9623. normal.scale(dist, tmp);
  9624. localSpherePos.vsub(tmp, tmp); // tmp is now the sphere position projected to the triangle plane
  9625. dist = tmp.distanceTo(localSpherePos);
  9626. if (Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius) {
  9627. if (justTest) {
  9628. return true;
  9629. }
  9630. let r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape, rsi, rsj);
  9631. tmp.vsub(localSpherePos, r.ni);
  9632. r.ni.normalize();
  9633. r.ni.scale(sphereShape.radius, r.ri);
  9634. r.ri.vadd(spherePos, r.ri);
  9635. r.ri.vsub(sphereBody.position, r.ri);
  9636. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  9637. tmp.vsub(trimeshBody.position, r.rj);
  9638. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  9639. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  9640. this.result.push(r);
  9641. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9642. }
  9643. }
  9644. triangles.length = 0;
  9645. }
  9646. planeTrimesh(planeShape, trimeshShape, planePos, trimeshPos, planeQuat, trimeshQuat, planeBody, trimeshBody, rsi, rsj, justTest) {
  9647. // Make contacts!
  9648. const v = new Vec3();
  9649. const normal = planeTrimesh_normal;
  9650. normal.set(0, 0, 1);
  9651. planeQuat.vmult(normal, normal); // Turn normal according to plane
  9652. for (let i = 0; i < trimeshShape.vertices.length / 3; i++) {
  9653. // Get world vertex from trimesh
  9654. trimeshShape.getVertex(i, v); // Safe up
  9655. const v2 = new Vec3();
  9656. v2.copy(v);
  9657. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v); // Check plane side
  9658. const relpos = planeTrimesh_relpos;
  9659. v.vsub(planePos, relpos);
  9660. const dot = normal.dot(relpos);
  9661. if (dot <= 0.0) {
  9662. if (justTest) {
  9663. return true;
  9664. }
  9665. const r = this.createContactEquation(planeBody, trimeshBody, planeShape, trimeshShape, rsi, rsj);
  9666. r.ni.copy(normal); // Contact normal is the plane normal
  9667. // Get vertex position projected on plane
  9668. const projected = planeTrimesh_projected;
  9669. normal.scale(relpos.dot(normal), projected);
  9670. v.vsub(projected, projected); // ri is the projected world position minus plane position
  9671. r.ri.copy(projected);
  9672. r.ri.vsub(planeBody.position, r.ri);
  9673. r.rj.copy(v);
  9674. r.rj.vsub(trimeshBody.position, r.rj); // Store result
  9675. this.result.push(r);
  9676. this.createFrictionEquationsFromContact(r, this.frictionResult);
  9677. }
  9678. }
  9679. } // convexTrimesh(
  9680. // si: ConvexPolyhedron, sj: Trimesh, xi: Vec3, xj: Vec3, qi: Quaternion, qj: Quaternion,
  9681. // bi: Body, bj: Body, rsi?: Shape | null, rsj?: Shape | null,
  9682. // faceListA?: number[] | null, faceListB?: number[] | null,
  9683. // ) {
  9684. // const sepAxis = convexConvex_sepAxis;
  9685. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  9686. // return;
  9687. // }
  9688. // // Construct a temp hull for each triangle
  9689. // const hullB = new ConvexPolyhedron();
  9690. // hullB.faces = [[0,1,2]];
  9691. // const va = new Vec3();
  9692. // const vb = new Vec3();
  9693. // const vc = new Vec3();
  9694. // hullB.vertices = [
  9695. // va,
  9696. // vb,
  9697. // vc
  9698. // ];
  9699. // for (let i = 0; i < sj.indices.length / 3; i++) {
  9700. // const triangleNormal = new Vec3();
  9701. // sj.getNormal(i, triangleNormal);
  9702. // hullB.faceNormals = [triangleNormal];
  9703. // sj.getTriangleVertices(i, va, vb, vc);
  9704. // let d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  9705. // if(!d){
  9706. // triangleNormal.scale(-1, triangleNormal);
  9707. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  9708. // if(!d){
  9709. // continue;
  9710. // }
  9711. // }
  9712. // const res: ConvexPolyhedronContactPoint[] = [];
  9713. // const q = convexConvex_q;
  9714. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  9715. // for(let j = 0; j !== res.length; j++){
  9716. // const r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  9717. // ri = r.ri,
  9718. // rj = r.rj;
  9719. // r.ni.copy(triangleNormal);
  9720. // r.ni.negate(r.ni);
  9721. // res[j].normal.negate(q);
  9722. // q.mult(res[j].depth, q);
  9723. // res[j].point.vadd(q, ri);
  9724. // rj.copy(res[j].point);
  9725. // // Contact points are in world coordinates. Transform back to relative
  9726. // ri.vsub(xi,ri);
  9727. // rj.vsub(xj,rj);
  9728. // // Make relative to bodies
  9729. // ri.vadd(xi, ri);
  9730. // ri.vsub(bi.position, ri);
  9731. // rj.vadd(xj, rj);
  9732. // rj.vsub(bj.position, rj);
  9733. // result.push(r);
  9734. // }
  9735. // }
  9736. // }
  9737. }
  9738. const averageNormal = new Vec3();
  9739. const averageContactPointA = new Vec3();
  9740. const averageContactPointB = new Vec3();
  9741. const tmpVec1 = new Vec3();
  9742. const tmpVec2 = new Vec3();
  9743. const tmpQuat1 = new Quaternion();
  9744. const tmpQuat2 = new Quaternion();
  9745. const planeTrimesh_normal = new Vec3();
  9746. const planeTrimesh_relpos = new Vec3();
  9747. const planeTrimesh_projected = new Vec3();
  9748. const sphereTrimesh_normal = new Vec3();
  9749. const sphereTrimesh_relpos = new Vec3();
  9750. const sphereTrimesh_v = new Vec3();
  9751. const sphereTrimesh_v2 = new Vec3();
  9752. const sphereTrimesh_edgeVertexA = new Vec3();
  9753. const sphereTrimesh_edgeVertexB = new Vec3();
  9754. const sphereTrimesh_edgeVector = new Vec3();
  9755. const sphereTrimesh_edgeVectorUnit = new Vec3();
  9756. const sphereTrimesh_localSpherePos = new Vec3();
  9757. const sphereTrimesh_tmp = new Vec3();
  9758. const sphereTrimesh_va = new Vec3();
  9759. const sphereTrimesh_vb = new Vec3();
  9760. const sphereTrimesh_vc = new Vec3();
  9761. const sphereTrimesh_localSphereAABB = new AABB();
  9762. const sphereTrimesh_triangles = [];
  9763. const point_on_plane_to_sphere = new Vec3();
  9764. const plane_to_sphere_ortho = new Vec3(); // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  9765. const pointInPolygon_edge = new Vec3();
  9766. const pointInPolygon_edge_x_normal = new Vec3();
  9767. const pointInPolygon_vtp = new Vec3();
  9768. function pointInPolygon(verts, normal, p) {
  9769. let positiveResult = null;
  9770. const N = verts.length;
  9771. for (let i = 0; i !== N; i++) {
  9772. const v = verts[i]; // Get edge to the next vertex
  9773. const edge = pointInPolygon_edge;
  9774. verts[(i + 1) % N].vsub(v, edge); // Get cross product between polygon normal and the edge
  9775. const edge_x_normal = pointInPolygon_edge_x_normal; //const edge_x_normal = new Vec3();
  9776. edge.cross(normal, edge_x_normal); // Get vector between point and current vertex
  9777. const vertex_to_p = pointInPolygon_vtp;
  9778. p.vsub(v, vertex_to_p); // This dot product determines which side of the edge the point is
  9779. const r = edge_x_normal.dot(vertex_to_p); // If all such dot products have same sign, we are inside the polygon.
  9780. if (positiveResult === null || r > 0 && positiveResult === true || r <= 0 && positiveResult === false) {
  9781. if (positiveResult === null) {
  9782. positiveResult = r > 0;
  9783. }
  9784. continue;
  9785. } else {
  9786. return false; // Encountered some other sign. Exit.
  9787. }
  9788. } // If we got here, all dot products were of the same sign.
  9789. return true;
  9790. }
  9791. const box_to_sphere = new Vec3();
  9792. const sphereBox_ns = new Vec3();
  9793. const sphereBox_ns1 = new Vec3();
  9794. const sphereBox_ns2 = new Vec3();
  9795. const sphereBox_sides = [new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3(), new Vec3()];
  9796. const sphereBox_sphere_to_corner = new Vec3();
  9797. const sphereBox_side_ns = new Vec3();
  9798. const sphereBox_side_ns1 = new Vec3();
  9799. const sphereBox_side_ns2 = new Vec3();
  9800. const convex_to_sphere = new Vec3();
  9801. const sphereConvex_edge = new Vec3();
  9802. const sphereConvex_edgeUnit = new Vec3();
  9803. const sphereConvex_sphereToCorner = new Vec3();
  9804. const sphereConvex_worldCorner = new Vec3();
  9805. const sphereConvex_worldNormal = new Vec3();
  9806. const sphereConvex_worldPoint = new Vec3();
  9807. const sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  9808. const sphereConvex_penetrationVec = new Vec3();
  9809. const sphereConvex_sphereToWorldPoint = new Vec3();
  9810. const planeConvex_v = new Vec3();
  9811. const planeConvex_normal = new Vec3();
  9812. const planeConvex_relpos = new Vec3();
  9813. const planeConvex_projected = new Vec3();
  9814. const convexConvex_sepAxis = new Vec3();
  9815. const convexConvex_q = new Vec3();
  9816. const particlePlane_normal = new Vec3();
  9817. const particlePlane_relpos = new Vec3();
  9818. const particlePlane_projected = new Vec3();
  9819. const particleSphere_normal = new Vec3(); // WIP
  9820. const cqj = new Quaternion();
  9821. const convexParticle_local = new Vec3();
  9822. const convexParticle_penetratedFaceNormal = new Vec3();
  9823. const convexParticle_vertexToParticle = new Vec3();
  9824. const convexParticle_worldPenetrationVec = new Vec3();
  9825. const convexHeightfield_tmp1 = new Vec3();
  9826. const convexHeightfield_tmp2 = new Vec3();
  9827. const convexHeightfield_faceList = [0];
  9828. const sphereHeightfield_tmp1 = new Vec3();
  9829. const sphereHeightfield_tmp2 = new Vec3();
  9830. class OverlapKeeper {
  9831. /**
  9832. * @todo Remove useless constructor
  9833. */
  9834. constructor() {
  9835. this.current = void 0;
  9836. this.previous = void 0;
  9837. this.current = [];
  9838. this.previous = [];
  9839. }
  9840. /**
  9841. * getKey
  9842. */
  9843. getKey(i, j) {
  9844. if (j < i) {
  9845. const temp = j;
  9846. j = i;
  9847. i = temp;
  9848. }
  9849. return i << 16 | j;
  9850. }
  9851. /**
  9852. * set
  9853. */
  9854. set(i, j) {
  9855. // Insertion sort. This way the diff will have linear complexity.
  9856. const key = this.getKey(i, j);
  9857. const current = this.current;
  9858. let index = 0;
  9859. while (key > current[index]) {
  9860. index++;
  9861. }
  9862. if (key === current[index]) {
  9863. return; // Pair was already added
  9864. }
  9865. for (let j = current.length - 1; j >= index; j--) {
  9866. current[j + 1] = current[j];
  9867. }
  9868. current[index] = key;
  9869. }
  9870. /**
  9871. * tick
  9872. */
  9873. tick() {
  9874. const tmp = this.current;
  9875. this.current = this.previous;
  9876. this.previous = tmp;
  9877. this.current.length = 0;
  9878. }
  9879. /**
  9880. * getDiff
  9881. */
  9882. getDiff(additions, removals) {
  9883. const a = this.current;
  9884. const b = this.previous;
  9885. const al = a.length;
  9886. const bl = b.length;
  9887. let j = 0;
  9888. for (let i = 0; i < al; i++) {
  9889. let found = false;
  9890. const keyA = a[i];
  9891. while (keyA > b[j]) {
  9892. j++;
  9893. }
  9894. found = keyA === b[j];
  9895. if (!found) {
  9896. unpackAndPush(additions, keyA);
  9897. }
  9898. }
  9899. j = 0;
  9900. for (let i = 0; i < bl; i++) {
  9901. let found = false;
  9902. const keyB = b[i];
  9903. while (keyB > a[j]) {
  9904. j++;
  9905. }
  9906. found = a[j] === keyB;
  9907. if (!found) {
  9908. unpackAndPush(removals, keyB);
  9909. }
  9910. }
  9911. }
  9912. }
  9913. function unpackAndPush(array, key) {
  9914. array.push((key & 0xffff0000) >> 16, key & 0x0000ffff);
  9915. }
  9916. /**
  9917. * TupleDictionary
  9918. */
  9919. class TupleDictionary {
  9920. constructor() {
  9921. this.data = {
  9922. keys: []
  9923. };
  9924. }
  9925. /** get */
  9926. get(i, j) {
  9927. if (i > j) {
  9928. // swap
  9929. const temp = j;
  9930. j = i;
  9931. i = temp;
  9932. }
  9933. return this.data[i + "-" + j];
  9934. }
  9935. /** set */
  9936. set(i, j, value) {
  9937. if (i > j) {
  9938. const temp = j;
  9939. j = i;
  9940. i = temp;
  9941. }
  9942. const key = i + "-" + j; // Check if key already exists
  9943. if (!this.get(i, j)) {
  9944. this.data.keys.push(key);
  9945. }
  9946. this.data[key] = value;
  9947. }
  9948. /** reset */
  9949. reset() {
  9950. const data = this.data;
  9951. const keys = data.keys;
  9952. while (keys.length > 0) {
  9953. const key = keys.pop();
  9954. delete data[key];
  9955. }
  9956. }
  9957. }
  9958. /**
  9959. * The physics world
  9960. */
  9961. class World extends EventTarget {
  9962. /**
  9963. * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
  9964. */
  9965. /**
  9966. * Makes bodies go to sleep when they've been inactive.
  9967. * @default false
  9968. */
  9969. /**
  9970. * All the current contacts (instances of ContactEquation) in the world.
  9971. */
  9972. /**
  9973. * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
  9974. * @default 0
  9975. */
  9976. /**
  9977. * Set to true to use fast quaternion normalization. It is often enough accurate to use.
  9978. * If bodies tend to explode, set to false.
  9979. * @default false
  9980. */
  9981. /**
  9982. * The wall-clock time since simulation start.
  9983. */
  9984. /**
  9985. * Number of timesteps taken since start.
  9986. */
  9987. /**
  9988. * Default and last timestep sizes.
  9989. */
  9990. /**
  9991. * The gravity of the world.
  9992. */
  9993. /**
  9994. * The broadphase algorithm to use.
  9995. * @default NaiveBroadphase
  9996. */
  9997. /**
  9998. * All bodies in this world
  9999. */
  10000. /**
  10001. * True if any bodies are not sleeping, false if every body is sleeping.
  10002. */
  10003. /**
  10004. * The solver algorithm to use.
  10005. * @default GSSolver
  10006. */
  10007. /**
  10008. * collisionMatrix
  10009. */
  10010. /**
  10011. * CollisionMatrix from the previous step.
  10012. */
  10013. /**
  10014. * All added materials.
  10015. * @deprecated
  10016. * @todo Remove
  10017. */
  10018. /**
  10019. * All added contactmaterials.
  10020. */
  10021. /**
  10022. * Used to look up a ContactMaterial given two instances of Material.
  10023. */
  10024. /**
  10025. * The default material of the bodies.
  10026. */
  10027. /**
  10028. * This contact material is used if no suitable contactmaterial is found for a contact.
  10029. */
  10030. /**
  10031. * Time accumulator for interpolation.
  10032. * @see https://gafferongames.com/game-physics/fix-your-timestep/
  10033. */
  10034. /**
  10035. * Dispatched after a body has been added to the world.
  10036. */
  10037. /**
  10038. * Dispatched after a body has been removed from the world.
  10039. */
  10040. constructor(options = {}) {
  10041. super();
  10042. this.dt = void 0;
  10043. this.allowSleep = void 0;
  10044. this.contacts = void 0;
  10045. this.frictionEquations = void 0;
  10046. this.quatNormalizeSkip = void 0;
  10047. this.quatNormalizeFast = void 0;
  10048. this.time = void 0;
  10049. this.stepnumber = void 0;
  10050. this.default_dt = void 0;
  10051. this.nextId = void 0;
  10052. this.gravity = void 0;
  10053. this.broadphase = void 0;
  10054. this.bodies = void 0;
  10055. this.hasActiveBodies = void 0;
  10056. this.solver = void 0;
  10057. this.constraints = void 0;
  10058. this.narrowphase = void 0;
  10059. this.collisionMatrix = void 0;
  10060. this.collisionMatrixPrevious = void 0;
  10061. this.bodyOverlapKeeper = void 0;
  10062. this.shapeOverlapKeeper = void 0;
  10063. this.materials = void 0;
  10064. this.contactmaterials = void 0;
  10065. this.contactMaterialTable = void 0;
  10066. this.defaultMaterial = void 0;
  10067. this.defaultContactMaterial = void 0;
  10068. this.doProfiling = void 0;
  10069. this.profile = void 0;
  10070. this.accumulator = void 0;
  10071. this.subsystems = void 0;
  10072. this.addBodyEvent = void 0;
  10073. this.removeBodyEvent = void 0;
  10074. this.idToBodyMap = void 0;
  10075. this.dt = -1;
  10076. this.allowSleep = !!options.allowSleep;
  10077. this.contacts = [];
  10078. this.frictionEquations = [];
  10079. this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;
  10080. this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;
  10081. this.time = 0.0;
  10082. this.stepnumber = 0;
  10083. this.default_dt = 1 / 60;
  10084. this.nextId = 0;
  10085. this.gravity = new Vec3();
  10086. if (options.gravity) {
  10087. this.gravity.copy(options.gravity);
  10088. }
  10089. this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();
  10090. this.bodies = [];
  10091. this.hasActiveBodies = false;
  10092. this.solver = options.solver !== undefined ? options.solver : new GSSolver();
  10093. this.constraints = [];
  10094. this.narrowphase = new Narrowphase(this);
  10095. this.collisionMatrix = new ArrayCollisionMatrix();
  10096. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  10097. this.bodyOverlapKeeper = new OverlapKeeper();
  10098. this.shapeOverlapKeeper = new OverlapKeeper();
  10099. this.materials = [];
  10100. this.contactmaterials = [];
  10101. this.contactMaterialTable = new TupleDictionary();
  10102. this.defaultMaterial = new Material('default');
  10103. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, {
  10104. friction: 0.3,
  10105. restitution: 0.0
  10106. });
  10107. this.doProfiling = false;
  10108. this.profile = {
  10109. solve: 0,
  10110. makeContactConstraints: 0,
  10111. broadphase: 0,
  10112. integrate: 0,
  10113. narrowphase: 0
  10114. };
  10115. this.accumulator = 0;
  10116. this.subsystems = [];
  10117. this.addBodyEvent = {
  10118. type: 'addBody',
  10119. body: null
  10120. };
  10121. this.removeBodyEvent = {
  10122. type: 'removeBody',
  10123. body: null
  10124. };
  10125. this.idToBodyMap = {};
  10126. this.broadphase.setWorld(this);
  10127. }
  10128. /**
  10129. * Get the contact material between materials m1 and m2
  10130. * @return The contact material if it was found.
  10131. */
  10132. getContactMaterial(m1, m2) {
  10133. return this.contactMaterialTable.get(m1.id, m2.id);
  10134. }
  10135. /**
  10136. * Get number of objects in the world.
  10137. * @deprecated
  10138. */
  10139. numObjects() {
  10140. return this.bodies.length;
  10141. }
  10142. /**
  10143. * Store old collision state info
  10144. */
  10145. collisionMatrixTick() {
  10146. const temp = this.collisionMatrixPrevious;
  10147. this.collisionMatrixPrevious = this.collisionMatrix;
  10148. this.collisionMatrix = temp;
  10149. this.collisionMatrix.reset();
  10150. this.bodyOverlapKeeper.tick();
  10151. this.shapeOverlapKeeper.tick();
  10152. }
  10153. /**
  10154. * Add a constraint to the simulation.
  10155. */
  10156. addConstraint(c) {
  10157. this.constraints.push(c);
  10158. }
  10159. /**
  10160. * Removes a constraint
  10161. */
  10162. removeConstraint(c) {
  10163. const idx = this.constraints.indexOf(c);
  10164. if (idx !== -1) {
  10165. this.constraints.splice(idx, 1);
  10166. }
  10167. }
  10168. /**
  10169. * Raycast test
  10170. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  10171. */
  10172. rayTest(from, to, result) {
  10173. if (result instanceof RaycastResult) {
  10174. // Do raycastClosest
  10175. this.raycastClosest(from, to, {
  10176. skipBackfaces: true
  10177. }, result);
  10178. } else {
  10179. // Do raycastAll
  10180. this.raycastAll(from, to, {
  10181. skipBackfaces: true
  10182. }, result);
  10183. }
  10184. }
  10185. /**
  10186. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  10187. * @return True if any body was hit.
  10188. */
  10189. raycastAll(from, to, options = {}, callback) {
  10190. options.mode = Ray.ALL;
  10191. options.from = from;
  10192. options.to = to;
  10193. options.callback = callback;
  10194. return tmpRay.intersectWorld(this, options);
  10195. }
  10196. /**
  10197. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  10198. * @return True if any body was hit.
  10199. */
  10200. raycastAny(from, to, options = {}, result) {
  10201. options.mode = Ray.ANY;
  10202. options.from = from;
  10203. options.to = to;
  10204. options.result = result;
  10205. return tmpRay.intersectWorld(this, options);
  10206. }
  10207. /**
  10208. * Ray cast, and return information of the closest hit.
  10209. * @return True if any body was hit.
  10210. */
  10211. raycastClosest(from, to, options = {}, result) {
  10212. options.mode = Ray.CLOSEST;
  10213. options.from = from;
  10214. options.to = to;
  10215. options.result = result;
  10216. return tmpRay.intersectWorld(this, options);
  10217. }
  10218. /**
  10219. * Add a rigid body to the simulation.
  10220. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  10221. * @todo Adding an array of bodies should be possible. This would save some loops too
  10222. */
  10223. addBody(body) {
  10224. if (this.bodies.includes(body)) {
  10225. return;
  10226. }
  10227. body.index = this.bodies.length;
  10228. this.bodies.push(body);
  10229. body.world = this;
  10230. body.initPosition.copy(body.position);
  10231. body.initVelocity.copy(body.velocity);
  10232. body.timeLastSleepy = this.time;
  10233. if (body instanceof Body) {
  10234. body.initAngularVelocity.copy(body.angularVelocity);
  10235. body.initQuaternion.copy(body.quaternion);
  10236. }
  10237. this.collisionMatrix.setNumObjects(this.bodies.length);
  10238. this.addBodyEvent.body = body;
  10239. this.idToBodyMap[body.id] = body;
  10240. this.dispatchEvent(this.addBodyEvent);
  10241. }
  10242. /**
  10243. * Remove a rigid body from the simulation.
  10244. */
  10245. removeBody(body) {
  10246. body.world = null;
  10247. const n = this.bodies.length - 1;
  10248. const bodies = this.bodies;
  10249. const idx = bodies.indexOf(body);
  10250. if (idx !== -1) {
  10251. bodies.splice(idx, 1); // Todo: should use a garbage free method
  10252. // Recompute index
  10253. for (let i = 0; i !== bodies.length; i++) {
  10254. bodies[i].index = i;
  10255. }
  10256. this.collisionMatrix.setNumObjects(n);
  10257. this.removeBodyEvent.body = body;
  10258. delete this.idToBodyMap[body.id];
  10259. this.dispatchEvent(this.removeBodyEvent);
  10260. }
  10261. }
  10262. getBodyById(id) {
  10263. return this.idToBodyMap[id];
  10264. }
  10265. /**
  10266. * @todo Make a faster map
  10267. */
  10268. getShapeById(id) {
  10269. const bodies = this.bodies;
  10270. for (let i = 0; i < bodies.length; i++) {
  10271. const shapes = bodies[i].shapes;
  10272. for (let j = 0; j < shapes.length; j++) {
  10273. const shape = shapes[j];
  10274. if (shape.id === id) {
  10275. return shape;
  10276. }
  10277. }
  10278. }
  10279. return null;
  10280. }
  10281. /**
  10282. * Adds a material to the World.
  10283. * @deprecated
  10284. * @todo Remove
  10285. */
  10286. addMaterial(m) {
  10287. this.materials.push(m);
  10288. }
  10289. /**
  10290. * Adds a contact material to the World
  10291. */
  10292. addContactMaterial(cmat) {
  10293. // Add contact material
  10294. this.contactmaterials.push(cmat); // Add current contact material to the material table
  10295. this.contactMaterialTable.set(cmat.materials[0].id, cmat.materials[1].id, cmat);
  10296. }
  10297. /**
  10298. * Step the physics world forward in time.
  10299. *
  10300. * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
  10301. *
  10302. * @param dt The fixed time step size to use.
  10303. * @param timeSinceLastCalled The time elapsed since the function was last called.
  10304. * @param maxSubSteps Maximum number of fixed steps to take per function call.
  10305. * @see https://web.archive.org/web/20180426154531/http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World#What_do_the_parameters_to_btDynamicsWorld::stepSimulation_mean.3F
  10306. * @example
  10307. * // fixed timestepping without interpolation
  10308. * world.step(1 / 60)
  10309. */
  10310. step(dt, timeSinceLastCalled, maxSubSteps = 10) {
  10311. if (timeSinceLastCalled === undefined) {
  10312. // Fixed, simple stepping
  10313. this.internalStep(dt); // Increment time
  10314. this.time += dt;
  10315. } else {
  10316. this.accumulator += timeSinceLastCalled;
  10317. const t0 = performance.now();
  10318. let substeps = 0;
  10319. while (this.accumulator >= dt && substeps < maxSubSteps) {
  10320. // Do fixed steps to catch up
  10321. this.internalStep(dt);
  10322. this.accumulator -= dt;
  10323. substeps++;
  10324. if (performance.now() - t0 > dt * 1000) {
  10325. // The framerate is not interactive anymore.
  10326. // We are below the target framerate.
  10327. // Better bail out.
  10328. break;
  10329. }
  10330. } // Remove the excess accumulator, since we may not
  10331. // have had enough substeps available to catch up
  10332. this.accumulator = this.accumulator % dt;
  10333. const t = this.accumulator / dt;
  10334. for (let j = 0; j !== this.bodies.length; j++) {
  10335. const b = this.bodies[j];
  10336. b.previousPosition.lerp(b.position, t, b.interpolatedPosition);
  10337. b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);
  10338. b.previousQuaternion.normalize();
  10339. }
  10340. this.time += timeSinceLastCalled;
  10341. }
  10342. }
  10343. internalStep(dt) {
  10344. this.dt = dt;
  10345. const contacts = this.contacts;
  10346. const p1 = World_step_p1;
  10347. const p2 = World_step_p2;
  10348. const N = this.numObjects();
  10349. const bodies = this.bodies;
  10350. const solver = this.solver;
  10351. const gravity = this.gravity;
  10352. const doProfiling = this.doProfiling;
  10353. const profile = this.profile;
  10354. const DYNAMIC = Body.DYNAMIC;
  10355. let profilingStart = -Infinity;
  10356. const constraints = this.constraints;
  10357. const frictionEquationPool = World_step_frictionEquationPool;
  10358. gravity.length();
  10359. const gx = gravity.x;
  10360. const gy = gravity.y;
  10361. const gz = gravity.z;
  10362. let i = 0;
  10363. if (doProfiling) {
  10364. profilingStart = performance.now();
  10365. } // Add gravity to all objects
  10366. for (i = 0; i !== N; i++) {
  10367. const bi = bodies[i];
  10368. if (bi.type === DYNAMIC) {
  10369. // Only for dynamic bodies
  10370. const f = bi.force;
  10371. const m = bi.mass;
  10372. f.x += m * gx;
  10373. f.y += m * gy;
  10374. f.z += m * gz;
  10375. }
  10376. } // Update subsystems
  10377. for (let i = 0, Nsubsystems = this.subsystems.length; i !== Nsubsystems; i++) {
  10378. this.subsystems[i].update();
  10379. } // Collision detection
  10380. if (doProfiling) {
  10381. profilingStart = performance.now();
  10382. }
  10383. p1.length = 0; // Clean up pair arrays from last step
  10384. p2.length = 0;
  10385. this.broadphase.collisionPairs(this, p1, p2);
  10386. if (doProfiling) {
  10387. profile.broadphase = performance.now() - profilingStart;
  10388. } // Remove constrained pairs with collideConnected == false
  10389. let Nconstraints = constraints.length;
  10390. for (i = 0; i !== Nconstraints; i++) {
  10391. const c = constraints[i];
  10392. if (!c.collideConnected) {
  10393. for (let j = p1.length - 1; j >= 0; j -= 1) {
  10394. if (c.bodyA === p1[j] && c.bodyB === p2[j] || c.bodyB === p1[j] && c.bodyA === p2[j]) {
  10395. p1.splice(j, 1);
  10396. p2.splice(j, 1);
  10397. }
  10398. }
  10399. }
  10400. }
  10401. this.collisionMatrixTick(); // Generate contacts
  10402. if (doProfiling) {
  10403. profilingStart = performance.now();
  10404. }
  10405. const oldcontacts = World_step_oldContacts;
  10406. const NoldContacts = contacts.length;
  10407. for (i = 0; i !== NoldContacts; i++) {
  10408. oldcontacts.push(contacts[i]);
  10409. }
  10410. contacts.length = 0; // Transfer FrictionEquation from current list to the pool for reuse
  10411. const NoldFrictionEquations = this.frictionEquations.length;
  10412. for (i = 0; i !== NoldFrictionEquations; i++) {
  10413. frictionEquationPool.push(this.frictionEquations[i]);
  10414. }
  10415. this.frictionEquations.length = 0;
  10416. this.narrowphase.getContacts(p1, p2, this, contacts, oldcontacts, // To be reused
  10417. this.frictionEquations, frictionEquationPool);
  10418. if (doProfiling) {
  10419. profile.narrowphase = performance.now() - profilingStart;
  10420. } // Loop over all collisions
  10421. if (doProfiling) {
  10422. profilingStart = performance.now();
  10423. } // Add all friction eqs
  10424. for (i = 0; i < this.frictionEquations.length; i++) {
  10425. solver.addEquation(this.frictionEquations[i]);
  10426. }
  10427. const ncontacts = contacts.length;
  10428. for (let k = 0; k !== ncontacts; k++) {
  10429. // Current contact
  10430. const c = contacts[k]; // Get current collision indeces
  10431. const bi = c.bi;
  10432. const bj = c.bj;
  10433. const si = c.si;
  10434. const sj = c.sj; // Get collision properties
  10435. let cm;
  10436. if (bi.material && bj.material) {
  10437. cm = this.getContactMaterial(bi.material, bj.material) || this.defaultContactMaterial;
  10438. } else {
  10439. cm = this.defaultContactMaterial;
  10440. } // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  10441. cm.friction; // c.restitution = cm.restitution;
  10442. // If friction or restitution were specified in the material, use them
  10443. if (bi.material && bj.material) {
  10444. if (bi.material.friction >= 0 && bj.material.friction >= 0) {
  10445. bi.material.friction * bj.material.friction;
  10446. }
  10447. if (bi.material.restitution >= 0 && bj.material.restitution >= 0) {
  10448. c.restitution = bi.material.restitution * bj.material.restitution;
  10449. }
  10450. } // c.setSpookParams(
  10451. // cm.contactEquationStiffness,
  10452. // cm.contactEquationRelaxation,
  10453. // dt
  10454. // );
  10455. solver.addEquation(c); // // Add friction constraint equation
  10456. // if(mu > 0){
  10457. // // Create 2 tangent equations
  10458. // const mug = mu * gnorm;
  10459. // const reducedMass = (bi.invMass + bj.invMass);
  10460. // if(reducedMass > 0){
  10461. // reducedMass = 1/reducedMass;
  10462. // }
  10463. // const pool = frictionEquationPool;
  10464. // const c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  10465. // const c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  10466. // this.frictionEquations.push(c1, c2);
  10467. // c1.bi = c2.bi = bi;
  10468. // c1.bj = c2.bj = bj;
  10469. // c1.minForce = c2.minForce = -mug*reducedMass;
  10470. // c1.maxForce = c2.maxForce = mug*reducedMass;
  10471. // // Copy over the relative vectors
  10472. // c1.ri.copy(c.ri);
  10473. // c1.rj.copy(c.rj);
  10474. // c2.ri.copy(c.ri);
  10475. // c2.rj.copy(c.rj);
  10476. // // Construct tangents
  10477. // c.ni.tangents(c1.t, c2.t);
  10478. // // Set spook params
  10479. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  10480. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  10481. // c1.enabled = c2.enabled = c.enabled;
  10482. // // Add equations to solver
  10483. // solver.addEquation(c1);
  10484. // solver.addEquation(c2);
  10485. // }
  10486. if (bi.allowSleep && bi.type === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.type !== Body.STATIC) {
  10487. const speedSquaredB = bj.velocity.lengthSquared() + bj.angularVelocity.lengthSquared();
  10488. const speedLimitSquaredB = bj.sleepSpeedLimit ** 2;
  10489. if (speedSquaredB >= speedLimitSquaredB * 2) {
  10490. bi.wakeUpAfterNarrowphase = true;
  10491. }
  10492. }
  10493. if (bj.allowSleep && bj.type === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.type !== Body.STATIC) {
  10494. const speedSquaredA = bi.velocity.lengthSquared() + bi.angularVelocity.lengthSquared();
  10495. const speedLimitSquaredA = bi.sleepSpeedLimit ** 2;
  10496. if (speedSquaredA >= speedLimitSquaredA * 2) {
  10497. bj.wakeUpAfterNarrowphase = true;
  10498. }
  10499. } // Now we know that i and j are in contact. Set collision matrix state
  10500. this.collisionMatrix.set(bi, bj, true);
  10501. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  10502. // First contact!
  10503. // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
  10504. World_step_collideEvent.body = bj;
  10505. World_step_collideEvent.contact = c;
  10506. bi.dispatchEvent(World_step_collideEvent);
  10507. World_step_collideEvent.body = bi;
  10508. bj.dispatchEvent(World_step_collideEvent);
  10509. }
  10510. this.bodyOverlapKeeper.set(bi.id, bj.id);
  10511. this.shapeOverlapKeeper.set(si.id, sj.id);
  10512. }
  10513. this.emitContactEvents();
  10514. if (doProfiling) {
  10515. profile.makeContactConstraints = performance.now() - profilingStart;
  10516. profilingStart = performance.now();
  10517. } // Wake up bodies
  10518. for (i = 0; i !== N; i++) {
  10519. const bi = bodies[i];
  10520. if (bi.wakeUpAfterNarrowphase) {
  10521. bi.wakeUp();
  10522. bi.wakeUpAfterNarrowphase = false;
  10523. }
  10524. } // Add user-added constraints
  10525. Nconstraints = constraints.length;
  10526. for (i = 0; i !== Nconstraints; i++) {
  10527. const c = constraints[i];
  10528. c.update();
  10529. for (let j = 0, Neq = c.equations.length; j !== Neq; j++) {
  10530. const eq = c.equations[j];
  10531. solver.addEquation(eq);
  10532. }
  10533. } // Solve the constrained system
  10534. solver.solve(dt, this);
  10535. if (doProfiling) {
  10536. profile.solve = performance.now() - profilingStart;
  10537. } // Remove all contacts from solver
  10538. solver.removeAllEquations(); // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  10539. const pow = Math.pow;
  10540. for (i = 0; i !== N; i++) {
  10541. const bi = bodies[i];
  10542. if (bi.type & DYNAMIC) {
  10543. // Only for dynamic bodies
  10544. const ld = pow(1.0 - bi.linearDamping, dt);
  10545. const v = bi.velocity;
  10546. v.scale(ld, v);
  10547. const av = bi.angularVelocity;
  10548. if (av) {
  10549. const ad = pow(1.0 - bi.angularDamping, dt);
  10550. av.scale(ad, av);
  10551. }
  10552. }
  10553. }
  10554. this.dispatchEvent(World_step_preStepEvent); // Invoke pre-step callbacks
  10555. for (i = 0; i !== N; i++) {
  10556. const bi = bodies[i];
  10557. if (bi.preStep) {
  10558. bi.preStep.call(bi);
  10559. }
  10560. } // Leap frog
  10561. // vnew = v + h*f/m
  10562. // xnew = x + h*vnew
  10563. if (doProfiling) {
  10564. profilingStart = performance.now();
  10565. }
  10566. const stepnumber = this.stepnumber;
  10567. const quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;
  10568. const quatNormalizeFast = this.quatNormalizeFast;
  10569. for (i = 0; i !== N; i++) {
  10570. bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);
  10571. }
  10572. this.clearForces();
  10573. this.broadphase.dirty = true;
  10574. if (doProfiling) {
  10575. profile.integrate = performance.now() - profilingStart;
  10576. } // Update step number
  10577. this.stepnumber += 1;
  10578. this.dispatchEvent(World_step_postStepEvent); // Invoke post-step callbacks
  10579. for (i = 0; i !== N; i++) {
  10580. const bi = bodies[i];
  10581. const postStep = bi.postStep;
  10582. if (postStep) {
  10583. postStep.call(bi);
  10584. }
  10585. } // Sleeping update
  10586. let hasActiveBodies = true;
  10587. if (this.allowSleep) {
  10588. hasActiveBodies = false;
  10589. for (i = 0; i !== N; i++) {
  10590. const bi = bodies[i];
  10591. bi.sleepTick(this.time);
  10592. if (bi.sleepState !== Body.SLEEPING) {
  10593. hasActiveBodies = true;
  10594. }
  10595. }
  10596. }
  10597. this.hasActiveBodies = hasActiveBodies;
  10598. }
  10599. emitContactEvents() {
  10600. const hasBeginContact = this.hasAnyEventListener('beginContact');
  10601. const hasEndContact = this.hasAnyEventListener('endContact');
  10602. if (hasBeginContact || hasEndContact) {
  10603. this.bodyOverlapKeeper.getDiff(additions, removals);
  10604. }
  10605. if (hasBeginContact) {
  10606. for (let i = 0, l = additions.length; i < l; i += 2) {
  10607. beginContactEvent.bodyA = this.getBodyById(additions[i]);
  10608. beginContactEvent.bodyB = this.getBodyById(additions[i + 1]);
  10609. this.dispatchEvent(beginContactEvent);
  10610. }
  10611. beginContactEvent.bodyA = beginContactEvent.bodyB = null;
  10612. }
  10613. if (hasEndContact) {
  10614. for (let i = 0, l = removals.length; i < l; i += 2) {
  10615. endContactEvent.bodyA = this.getBodyById(removals[i]);
  10616. endContactEvent.bodyB = this.getBodyById(removals[i + 1]);
  10617. this.dispatchEvent(endContactEvent);
  10618. }
  10619. endContactEvent.bodyA = endContactEvent.bodyB = null;
  10620. }
  10621. additions.length = removals.length = 0;
  10622. const hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');
  10623. const hasEndShapeContact = this.hasAnyEventListener('endShapeContact');
  10624. if (hasBeginShapeContact || hasEndShapeContact) {
  10625. this.shapeOverlapKeeper.getDiff(additions, removals);
  10626. }
  10627. if (hasBeginShapeContact) {
  10628. for (let i = 0, l = additions.length; i < l; i += 2) {
  10629. const shapeA = this.getShapeById(additions[i]);
  10630. const shapeB = this.getShapeById(additions[i + 1]);
  10631. beginShapeContactEvent.shapeA = shapeA;
  10632. beginShapeContactEvent.shapeB = shapeB;
  10633. if (shapeA) beginShapeContactEvent.bodyA = shapeA.body;
  10634. if (shapeB) beginShapeContactEvent.bodyB = shapeB.body;
  10635. this.dispatchEvent(beginShapeContactEvent);
  10636. }
  10637. beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;
  10638. }
  10639. if (hasEndShapeContact) {
  10640. for (let i = 0, l = removals.length; i < l; i += 2) {
  10641. const shapeA = this.getShapeById(removals[i]);
  10642. const shapeB = this.getShapeById(removals[i + 1]);
  10643. endShapeContactEvent.shapeA = shapeA;
  10644. endShapeContactEvent.shapeB = shapeB;
  10645. if (shapeA) endShapeContactEvent.bodyA = shapeA.body;
  10646. if (shapeB) endShapeContactEvent.bodyB = shapeB.body;
  10647. this.dispatchEvent(endShapeContactEvent);
  10648. }
  10649. endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;
  10650. }
  10651. }
  10652. /**
  10653. * Sets all body forces in the world to zero.
  10654. */
  10655. clearForces() {
  10656. const bodies = this.bodies;
  10657. const N = bodies.length;
  10658. for (let i = 0; i !== N; i++) {
  10659. const b = bodies[i];
  10660. b.force;
  10661. b.torque;
  10662. b.force.set(0, 0, 0);
  10663. b.torque.set(0, 0, 0);
  10664. }
  10665. }
  10666. } // Temp stuff
  10667. new AABB();
  10668. const tmpRay = new Ray(); // performance.now() fallback on Date.now()
  10669. const performance = globalThis.performance || {};
  10670. if (!performance.now) {
  10671. let nowOffset = Date.now();
  10672. if (performance.timing && performance.timing.navigationStart) {
  10673. nowOffset = performance.timing.navigationStart;
  10674. }
  10675. performance.now = () => Date.now() - nowOffset;
  10676. }
  10677. // Reusable event objects to save memory.
  10678. const World_step_postStepEvent = {
  10679. type: 'postStep'
  10680. }; // Dispatched before the world steps forward in time.
  10681. const World_step_preStepEvent = {
  10682. type: 'preStep'
  10683. };
  10684. const World_step_collideEvent = {
  10685. type: Body.COLLIDE_EVENT_NAME,
  10686. body: null,
  10687. contact: null
  10688. }; // Pools for unused objects
  10689. const World_step_oldContacts = [];
  10690. const World_step_frictionEquationPool = []; // Reusable arrays for collision pairs
  10691. const World_step_p1 = [];
  10692. const World_step_p2 = []; // Stuff for emitContactEvents
  10693. const additions = [];
  10694. const removals = [];
  10695. const beginContactEvent = {
  10696. type: 'beginContact',
  10697. bodyA: null,
  10698. bodyB: null
  10699. };
  10700. const endContactEvent = {
  10701. type: 'endContact',
  10702. bodyA: null,
  10703. bodyB: null
  10704. };
  10705. const beginShapeContactEvent = {
  10706. type: 'beginShapeContact',
  10707. bodyA: null,
  10708. bodyB: null,
  10709. shapeA: null,
  10710. shapeB: null
  10711. };
  10712. const endShapeContactEvent = {
  10713. type: 'endShapeContact',
  10714. bodyA: null,
  10715. bodyB: null,
  10716. shapeA: null,
  10717. shapeB: null
  10718. };
  10719. export { AABB, ArrayCollisionMatrix, BODY_SLEEP_STATES, BODY_TYPES, Body, Box, Broadphase, COLLISION_TYPES, ConeTwistConstraint, Constraint, ContactEquation, ContactMaterial, ConvexPolyhedron, Cylinder, DistanceConstraint, Equation, EventTarget, FrictionEquation, GSSolver, GridBroadphase, Heightfield, HingeConstraint, JacobianElement, LockConstraint, Mat3, Material, NaiveBroadphase, Narrowphase, ObjectCollisionMatrix, Particle, Plane, PointToPointConstraint, Pool, Quaternion, RAY_MODES, Ray, RaycastResult, RaycastVehicle, RigidVehicle, RotationalEquation, RotationalMotorEquation, SAPBroadphase, SHAPE_TYPES, SPHSystem, Shape, Solver, Sphere, SplitSolver, Spring, Transform, Trimesh, Vec3, Vec3Pool, WheelInfo, World };