xatlas.cpp 325 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045
  1. /*
  2. MIT License
  3. Copyright (c) 2018-2020 Jonathan Young
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. /*
  21. thekla_atlas
  22. https://github.com/Thekla/thekla_atlas
  23. MIT License
  24. Copyright (c) 2013 Thekla, Inc
  25. Copyright NVIDIA Corporation 2006 -- Ignacio Castano <icastano@nvidia.com>
  26. Fast-BVH
  27. https://github.com/brandonpelfrey/Fast-BVH
  28. MIT License
  29. Copyright (c) 2012 Brandon Pelfrey
  30. */
  31. #include "xatlas.h"
  32. #ifndef XATLAS_C_API
  33. #define XATLAS_C_API 0
  34. #endif
  35. #if XATLAS_C_API
  36. #include "xatlas_c.h"
  37. #endif
  38. #include <atomic>
  39. #include <condition_variable>
  40. #include <mutex>
  41. #include <thread>
  42. #include <assert.h>
  43. #include <float.h> // FLT_MAX
  44. #include <limits.h>
  45. #include <math.h>
  46. #define __STDC_LIMIT_MACROS
  47. #include <stdint.h>
  48. #include <stdio.h>
  49. #include <string.h>
  50. #ifndef XA_DEBUG
  51. #ifdef NDEBUG
  52. #define XA_DEBUG 0
  53. #else
  54. #define XA_DEBUG 1
  55. #endif
  56. #endif
  57. #ifndef XA_PROFILE
  58. #define XA_PROFILE 0
  59. #endif
  60. #if XA_PROFILE
  61. #include <chrono>
  62. #endif
  63. #ifndef XA_MULTITHREADED
  64. #define XA_MULTITHREADED 1
  65. #endif
  66. #define XA_STR(x) #x
  67. #define XA_XSTR(x) XA_STR(x)
  68. #ifndef XA_ASSERT
  69. #define XA_ASSERT(exp) if (!(exp)) { XA_PRINT_WARNING("\rASSERT: %s %s %d\n", XA_XSTR(exp), __FILE__, __LINE__); }
  70. #endif
  71. #ifndef XA_DEBUG_ASSERT
  72. #define XA_DEBUG_ASSERT(exp) assert(exp)
  73. #endif
  74. #ifndef XA_PRINT
  75. #define XA_PRINT(...) \
  76. if (xatlas::internal::s_print && xatlas::internal::s_printVerbose) \
  77. xatlas::internal::s_print(__VA_ARGS__);
  78. #endif
  79. #ifndef XA_PRINT_WARNING
  80. #define XA_PRINT_WARNING(...) \
  81. if (xatlas::internal::s_print) \
  82. xatlas::internal::s_print(__VA_ARGS__);
  83. #endif
  84. #define XA_ALLOC(tag, type) (type *)internal::Realloc(nullptr, sizeof(type), tag, __FILE__, __LINE__)
  85. #define XA_ALLOC_ARRAY(tag, type, num) (type *)internal::Realloc(nullptr, sizeof(type) * (num), tag, __FILE__, __LINE__)
  86. #define XA_REALLOC(tag, ptr, type, num) (type *)internal::Realloc(ptr, sizeof(type) * (num), tag, __FILE__, __LINE__)
  87. #define XA_REALLOC_SIZE(tag, ptr, size) (uint8_t *)internal::Realloc(ptr, size, tag, __FILE__, __LINE__)
  88. #define XA_FREE(ptr) internal::Realloc(ptr, 0, internal::MemTag::Default, __FILE__, __LINE__)
  89. #define XA_NEW(tag, type) new (XA_ALLOC(tag, type)) type()
  90. #define XA_NEW_ARGS(tag, type, ...) new (XA_ALLOC(tag, type)) type(__VA_ARGS__)
  91. #ifdef _MSC_VER
  92. #define XA_INLINE __forceinline
  93. #else
  94. #define XA_INLINE inline
  95. #endif
  96. #if defined(__clang__) || defined(__GNUC__)
  97. #define XA_NODISCARD [[nodiscard]]
  98. #elif defined(_MSC_VER)
  99. #define XA_NODISCARD _Check_return_
  100. #else
  101. #define XA_NODISCARD
  102. #endif
  103. #define XA_UNUSED(a) ((void)(a))
  104. #define XA_MERGE_CHARTS 1
  105. #define XA_MERGE_CHARTS_MIN_NORMAL_DEVIATION 0.5f
  106. #define XA_RECOMPUTE_CHARTS 1
  107. #define XA_CHECK_PARAM_WINDING 0
  108. #define XA_CHECK_PIECEWISE_CHART_QUALITY 0
  109. #define XA_CHECK_T_JUNCTIONS 0
  110. #define XA_DEBUG_HEAP 0
  111. #define XA_DEBUG_SINGLE_CHART 0
  112. #define XA_DEBUG_ALL_CHARTS_INVALID 0
  113. #define XA_DEBUG_EXPORT_ATLAS_IMAGES 0
  114. #define XA_DEBUG_EXPORT_ATLAS_IMAGES_PER_CHART 0 // Export an atlas image after each chart is added.
  115. #define XA_DEBUG_EXPORT_BOUNDARY_GRID 0
  116. #define XA_DEBUG_EXPORT_TGA (XA_DEBUG_EXPORT_ATLAS_IMAGES || XA_DEBUG_EXPORT_BOUNDARY_GRID)
  117. #define XA_DEBUG_EXPORT_OBJ_FACE_GROUPS 0
  118. #define XA_DEBUG_EXPORT_OBJ_CHART_GROUPS 0
  119. #define XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS 0
  120. #define XA_DEBUG_EXPORT_OBJ_CHARTS 0
  121. #define XA_DEBUG_EXPORT_OBJ_TJUNCTION 0 // XA_CHECK_T_JUNCTIONS must also be set
  122. #define XA_DEBUG_EXPORT_OBJ_CHARTS_AFTER_PARAMETERIZATION 0
  123. #define XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION 0
  124. #define XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS 0
  125. #define XA_DEBUG_EXPORT_OBJ (0 \
  126. || XA_DEBUG_EXPORT_OBJ_FACE_GROUPS \
  127. || XA_DEBUG_EXPORT_OBJ_CHART_GROUPS \
  128. || XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS \
  129. || XA_DEBUG_EXPORT_OBJ_CHARTS \
  130. || XA_DEBUG_EXPORT_OBJ_TJUNCTION \
  131. || XA_DEBUG_EXPORT_OBJ_CHARTS_AFTER_PARAMETERIZATION \
  132. || XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION \
  133. || XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS)
  134. #ifdef _MSC_VER
  135. #define XA_FOPEN(_file, _filename, _mode) { if (fopen_s(&_file, _filename, _mode) != 0) _file = NULL; }
  136. #define XA_SPRINTF(_buffer, _size, _format, ...) sprintf_s(_buffer, _size, _format, __VA_ARGS__)
  137. #else
  138. #define XA_FOPEN(_file, _filename, _mode) _file = fopen(_filename, _mode)
  139. #define XA_SPRINTF(_buffer, _size, _format, ...) sprintf(_buffer, _format, __VA_ARGS__)
  140. #endif
  141. namespace xatlas {
  142. namespace internal {
  143. static ReallocFunc s_realloc = realloc;
  144. static FreeFunc s_free = free;
  145. static PrintFunc s_print = printf;
  146. static bool s_printVerbose = false;
  147. #if XA_PROFILE
  148. typedef uint64_t Duration;
  149. #define XA_PROFILE_START(var) const std::chrono::time_point<std::chrono::high_resolution_clock> var##Start = std::chrono::high_resolution_clock::now();
  150. #define XA_PROFILE_END(var) internal::s_profile.var += uint64_t(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - var##Start).count());
  151. #define XA_PROFILE_PRINT_AND_RESET(label, var) XA_PRINT("%s%.2f seconds (%g ms)\n", label, internal::durationToSeconds(internal::s_profile.var), internal::durationToMs(internal::s_profile.var)); internal::s_profile.var = 0u;
  152. #define XA_PROFILE_ALLOC 0
  153. struct ProfileData
  154. {
  155. #if XA_PROFILE_ALLOC
  156. std::atomic<Duration> alloc;
  157. #endif
  158. std::chrono::time_point<std::chrono::high_resolution_clock> addMeshRealStart;
  159. Duration addMeshReal;
  160. Duration addMeshCopyData;
  161. std::atomic<Duration> addMeshThread;
  162. std::atomic<Duration> addMeshCreateColocals;
  163. Duration computeChartsReal;
  164. std::atomic<Duration> computeChartsThread;
  165. std::atomic<Duration> createFaceGroups;
  166. std::atomic<Duration> extractInvalidMeshGeometry;
  167. std::atomic<Duration> chartGroupComputeChartsReal;
  168. std::atomic<Duration> chartGroupComputeChartsThread;
  169. std::atomic<Duration> createChartGroupMesh;
  170. std::atomic<Duration> createChartGroupMeshColocals;
  171. std::atomic<Duration> createChartGroupMeshBoundaries;
  172. std::atomic<Duration> buildAtlas;
  173. std::atomic<Duration> buildAtlasInit;
  174. std::atomic<Duration> planarCharts;
  175. std::atomic<Duration> originalUvCharts;
  176. std::atomic<Duration> clusteredCharts;
  177. std::atomic<Duration> clusteredChartsPlaceSeeds;
  178. std::atomic<Duration> clusteredChartsPlaceSeedsBoundaryIntersection;
  179. std::atomic<Duration> clusteredChartsRelocateSeeds;
  180. std::atomic<Duration> clusteredChartsReset;
  181. std::atomic<Duration> clusteredChartsGrow;
  182. std::atomic<Duration> clusteredChartsGrowBoundaryIntersection;
  183. std::atomic<Duration> clusteredChartsMerge;
  184. std::atomic<Duration> clusteredChartsFillHoles;
  185. std::atomic<Duration> copyChartFaces;
  186. std::atomic<Duration> createChartMeshAndParameterizeReal;
  187. std::atomic<Duration> createChartMeshAndParameterizeThread;
  188. std::atomic<Duration> createChartMesh;
  189. std::atomic<Duration> parameterizeCharts;
  190. std::atomic<Duration> parameterizeChartsOrthogonal;
  191. std::atomic<Duration> parameterizeChartsLSCM;
  192. std::atomic<Duration> parameterizeChartsRecompute;
  193. std::atomic<Duration> parameterizeChartsPiecewise;
  194. std::atomic<Duration> parameterizeChartsPiecewiseBoundaryIntersection;
  195. std::atomic<Duration> parameterizeChartsEvaluateQuality;
  196. Duration packCharts;
  197. Duration packChartsAddCharts;
  198. std::atomic<Duration> packChartsAddChartsThread;
  199. std::atomic<Duration> packChartsAddChartsRestoreTexcoords;
  200. Duration packChartsRasterize;
  201. Duration packChartsDilate;
  202. Duration packChartsFindLocation;
  203. Duration packChartsBlit;
  204. Duration buildOutputMeshes;
  205. };
  206. static ProfileData s_profile;
  207. static double durationToMs(Duration c)
  208. {
  209. return (double)c * 0.001;
  210. }
  211. static double durationToSeconds(Duration c)
  212. {
  213. return (double)c * 0.000001;
  214. }
  215. #else
  216. #define XA_PROFILE_START(var)
  217. #define XA_PROFILE_END(var)
  218. #define XA_PROFILE_PRINT_AND_RESET(label, var)
  219. #define XA_PROFILE_ALLOC 0
  220. #endif
  221. struct MemTag
  222. {
  223. enum
  224. {
  225. Default,
  226. BitImage,
  227. BVH,
  228. Matrix,
  229. Mesh,
  230. MeshBoundaries,
  231. MeshColocals,
  232. MeshEdgeMap,
  233. MeshIndices,
  234. MeshNormals,
  235. MeshPositions,
  236. MeshTexcoords,
  237. OpenNL,
  238. SegmentAtlasChartCandidates,
  239. SegmentAtlasChartFaces,
  240. SegmentAtlasMeshData,
  241. SegmentAtlasPlanarRegions,
  242. Count
  243. };
  244. };
  245. #if XA_DEBUG_HEAP
  246. struct AllocHeader
  247. {
  248. size_t size;
  249. const char *file;
  250. int line;
  251. int tag;
  252. uint32_t id;
  253. AllocHeader *prev, *next;
  254. bool free;
  255. };
  256. static std::mutex s_allocMutex;
  257. static AllocHeader *s_allocRoot = nullptr;
  258. static size_t s_allocTotalCount = 0, s_allocTotalSize = 0, s_allocPeakSize = 0, s_allocCount[MemTag::Count] = { 0 }, s_allocTotalTagSize[MemTag::Count] = { 0 }, s_allocPeakTagSize[MemTag::Count] = { 0 };
  259. static uint32_t s_allocId =0 ;
  260. static constexpr uint32_t kAllocRedzone = 0x12345678;
  261. static void *Realloc(void *ptr, size_t size, int tag, const char *file, int line)
  262. {
  263. std::unique_lock<std::mutex> lock(s_allocMutex);
  264. if (!size && !ptr)
  265. return nullptr;
  266. uint8_t *realPtr = nullptr;
  267. AllocHeader *header = nullptr;
  268. if (ptr) {
  269. realPtr = ((uint8_t *)ptr) - sizeof(AllocHeader);
  270. header = (AllocHeader *)realPtr;
  271. }
  272. if (realPtr && size) {
  273. s_allocTotalSize -= header->size;
  274. s_allocTotalTagSize[header->tag] -= header->size;
  275. // realloc, remove.
  276. if (header->prev)
  277. header->prev->next = header->next;
  278. else
  279. s_allocRoot = header->next;
  280. if (header->next)
  281. header->next->prev = header->prev;
  282. }
  283. if (!size) {
  284. s_allocTotalSize -= header->size;
  285. s_allocTotalTagSize[header->tag] -= header->size;
  286. XA_ASSERT(!header->free); // double free
  287. header->free = true;
  288. return nullptr;
  289. }
  290. size += sizeof(AllocHeader) + sizeof(kAllocRedzone);
  291. uint8_t *newPtr = (uint8_t *)s_realloc(realPtr, size);
  292. if (!newPtr)
  293. return nullptr;
  294. header = (AllocHeader *)newPtr;
  295. header->size = size;
  296. header->file = file;
  297. header->line = line;
  298. header->tag = tag;
  299. header->id = s_allocId++;
  300. header->free = false;
  301. if (!s_allocRoot) {
  302. s_allocRoot = header;
  303. header->prev = header->next = 0;
  304. } else {
  305. header->prev = nullptr;
  306. header->next = s_allocRoot;
  307. s_allocRoot = header;
  308. header->next->prev = header;
  309. }
  310. s_allocTotalCount++;
  311. s_allocTotalSize += size;
  312. if (s_allocTotalSize > s_allocPeakSize)
  313. s_allocPeakSize = s_allocTotalSize;
  314. s_allocCount[tag]++;
  315. s_allocTotalTagSize[tag] += size;
  316. if (s_allocTotalTagSize[tag] > s_allocPeakTagSize[tag])
  317. s_allocPeakTagSize[tag] = s_allocTotalTagSize[tag];
  318. auto redzone = (uint32_t *)(newPtr + size - sizeof(kAllocRedzone));
  319. *redzone = kAllocRedzone;
  320. return newPtr + sizeof(AllocHeader);
  321. }
  322. static void ReportLeaks()
  323. {
  324. printf("Checking for memory leaks...\n");
  325. bool anyLeaks = false;
  326. AllocHeader *header = s_allocRoot;
  327. while (header) {
  328. if (!header->free) {
  329. printf(" Leak: ID %u, %zu bytes, %s %d\n", header->id, header->size, header->file, header->line);
  330. anyLeaks = true;
  331. }
  332. auto redzone = (const uint32_t *)((const uint8_t *)header + header->size - sizeof(kAllocRedzone));
  333. if (*redzone != kAllocRedzone)
  334. printf(" Redzone corrupted: %zu bytes %s %d\n", header->size, header->file, header->line);
  335. header = header->next;
  336. }
  337. if (!anyLeaks)
  338. printf(" No memory leaks\n");
  339. header = s_allocRoot;
  340. while (header) {
  341. AllocHeader *destroy = header;
  342. header = header->next;
  343. s_realloc(destroy, 0);
  344. }
  345. s_allocRoot = nullptr;
  346. s_allocTotalSize = s_allocPeakSize = 0;
  347. for (int i = 0; i < MemTag::Count; i++)
  348. s_allocTotalTagSize[i] = s_allocPeakTagSize[i] = 0;
  349. }
  350. static void PrintMemoryUsage()
  351. {
  352. XA_PRINT("Total allocations: %zu\n", s_allocTotalCount);
  353. XA_PRINT("Memory usage: %0.2fMB current, %0.2fMB peak\n", internal::s_allocTotalSize / 1024.0f / 1024.0f, internal::s_allocPeakSize / 1024.0f / 1024.0f);
  354. static const char *labels[] = { // Sync with MemTag
  355. "Default",
  356. "BitImage",
  357. "BVH",
  358. "Matrix",
  359. "Mesh",
  360. "MeshBoundaries",
  361. "MeshColocals",
  362. "MeshEdgeMap",
  363. "MeshIndices",
  364. "MeshNormals",
  365. "MeshPositions",
  366. "MeshTexcoords",
  367. "OpenNL",
  368. "SegmentAtlasChartCandidates",
  369. "SegmentAtlasChartFaces",
  370. "SegmentAtlasMeshData",
  371. "SegmentAtlasPlanarRegions"
  372. };
  373. for (int i = 0; i < MemTag::Count; i++) {
  374. XA_PRINT(" %s: %zu allocations, %0.2fMB current, %0.2fMB peak\n", labels[i], internal::s_allocCount[i], internal::s_allocTotalTagSize[i] / 1024.0f / 1024.0f, internal::s_allocPeakTagSize[i] / 1024.0f / 1024.0f);
  375. }
  376. }
  377. #define XA_PRINT_MEM_USAGE internal::PrintMemoryUsage();
  378. #else
  379. static void *Realloc(void *ptr, size_t size, int /*tag*/, const char * /*file*/, int /*line*/)
  380. {
  381. if (size == 0 && !ptr)
  382. return nullptr;
  383. if (size == 0 && s_free) {
  384. s_free(ptr);
  385. return nullptr;
  386. }
  387. #if XA_PROFILE_ALLOC
  388. XA_PROFILE_START(alloc)
  389. #endif
  390. void *mem = s_realloc(ptr, size);
  391. #if XA_PROFILE_ALLOC
  392. XA_PROFILE_END(alloc)
  393. #endif
  394. XA_DEBUG_ASSERT(size <= 0 || (size > 0 && mem));
  395. return mem;
  396. }
  397. #define XA_PRINT_MEM_USAGE
  398. #endif
  399. static constexpr float kPi = 3.14159265358979323846f;
  400. static constexpr float kPi2 = 6.28318530717958647692f;
  401. static constexpr float kEpsilon = 0.0001f;
  402. static constexpr float kAreaEpsilon = FLT_EPSILON;
  403. static constexpr float kNormalEpsilon = 0.001f;
  404. static int align(int x, int a)
  405. {
  406. return (x + a - 1) & ~(a - 1);
  407. }
  408. template <typename T>
  409. static T max(const T &a, const T &b)
  410. {
  411. return a > b ? a : b;
  412. }
  413. template <typename T>
  414. static T min(const T &a, const T &b)
  415. {
  416. return a < b ? a : b;
  417. }
  418. template <typename T>
  419. static T max3(const T &a, const T &b, const T &c)
  420. {
  421. return max(a, max(b, c));
  422. }
  423. /// Return the maximum of the three arguments.
  424. template <typename T>
  425. static T min3(const T &a, const T &b, const T &c)
  426. {
  427. return min(a, min(b, c));
  428. }
  429. /// Clamp between two values.
  430. template <typename T>
  431. static T clamp(const T &x, const T &a, const T &b)
  432. {
  433. return min(max(x, a), b);
  434. }
  435. template <typename T>
  436. static void swap(T &a, T &b)
  437. {
  438. T temp = a;
  439. a = b;
  440. b = temp;
  441. }
  442. union FloatUint32
  443. {
  444. float f;
  445. uint32_t u;
  446. };
  447. static bool isFinite(float f)
  448. {
  449. FloatUint32 fu;
  450. fu.f = f;
  451. return fu.u != 0x7F800000u && fu.u != 0x7F800001u;
  452. }
  453. static bool isNan(float f)
  454. {
  455. return f != f;
  456. }
  457. // Robust floating point comparisons:
  458. // http://realtimecollisiondetection.net/blog/?p=89
  459. static bool equal(const float f0, const float f1, const float epsilon)
  460. {
  461. //return fabs(f0-f1) <= epsilon;
  462. return fabs(f0 - f1) <= epsilon * max3(1.0f, fabsf(f0), fabsf(f1));
  463. }
  464. static int ftoi_ceil(float val)
  465. {
  466. return (int)ceilf(val);
  467. }
  468. static bool isZero(const float f, const float epsilon)
  469. {
  470. return fabs(f) <= epsilon;
  471. }
  472. static float square(float f)
  473. {
  474. return f * f;
  475. }
  476. /** Return the next power of two.
  477. * @see http://graphics.stanford.edu/~seander/bithacks.html
  478. * @warning Behaviour for 0 is undefined.
  479. * @note isPowerOfTwo(x) == true -> nextPowerOfTwo(x) == x
  480. * @note nextPowerOfTwo(x) = 2 << log2(x-1)
  481. */
  482. static uint32_t nextPowerOfTwo(uint32_t x)
  483. {
  484. XA_DEBUG_ASSERT( x != 0 );
  485. // On modern CPUs this is supposed to be as fast as using the bsr instruction.
  486. x--;
  487. x |= x >> 1;
  488. x |= x >> 2;
  489. x |= x >> 4;
  490. x |= x >> 8;
  491. x |= x >> 16;
  492. return x + 1;
  493. }
  494. class Vector2
  495. {
  496. public:
  497. Vector2() {}
  498. explicit Vector2(float f) : x(f), y(f) {}
  499. Vector2(float _x, float _y): x(_x), y(_y) {}
  500. Vector2 operator-() const
  501. {
  502. return Vector2(-x, -y);
  503. }
  504. void operator+=(const Vector2 &v)
  505. {
  506. x += v.x;
  507. y += v.y;
  508. }
  509. void operator-=(const Vector2 &v)
  510. {
  511. x -= v.x;
  512. y -= v.y;
  513. }
  514. void operator*=(float s)
  515. {
  516. x *= s;
  517. y *= s;
  518. }
  519. void operator*=(const Vector2 &v)
  520. {
  521. x *= v.x;
  522. y *= v.y;
  523. }
  524. float x, y;
  525. };
  526. static bool operator==(const Vector2 &a, const Vector2 &b)
  527. {
  528. return a.x == b.x && a.y == b.y;
  529. }
  530. static bool operator!=(const Vector2 &a, const Vector2 &b)
  531. {
  532. return a.x != b.x || a.y != b.y;
  533. }
  534. /*static Vector2 operator+(const Vector2 &a, const Vector2 &b)
  535. {
  536. return Vector2(a.x + b.x, a.y + b.y);
  537. }*/
  538. static Vector2 operator-(const Vector2 &a, const Vector2 &b)
  539. {
  540. return Vector2(a.x - b.x, a.y - b.y);
  541. }
  542. static Vector2 operator*(const Vector2 &v, float s)
  543. {
  544. return Vector2(v.x * s, v.y * s);
  545. }
  546. static float dot(const Vector2 &a, const Vector2 &b)
  547. {
  548. return a.x * b.x + a.y * b.y;
  549. }
  550. static float lengthSquared(const Vector2 &v)
  551. {
  552. return v.x * v.x + v.y * v.y;
  553. }
  554. static float length(const Vector2 &v)
  555. {
  556. return sqrtf(lengthSquared(v));
  557. }
  558. #if XA_DEBUG
  559. static bool isNormalized(const Vector2 &v, float epsilon = kNormalEpsilon)
  560. {
  561. return equal(length(v), 1, epsilon);
  562. }
  563. #endif
  564. static Vector2 normalize(const Vector2 &v)
  565. {
  566. const float l = length(v);
  567. XA_DEBUG_ASSERT(l > 0.0f); // Never negative.
  568. const Vector2 n = v * (1.0f / l);
  569. XA_DEBUG_ASSERT(isNormalized(n));
  570. return n;
  571. }
  572. static Vector2 normalizeSafe(const Vector2 &v, const Vector2 &fallback)
  573. {
  574. const float l = length(v);
  575. if (l > 0.0f) // Never negative.
  576. return v * (1.0f / l);
  577. return fallback;
  578. }
  579. static bool equal(const Vector2 &v1, const Vector2 &v2, float epsilon)
  580. {
  581. return equal(v1.x, v2.x, epsilon) && equal(v1.y, v2.y, epsilon);
  582. }
  583. static Vector2 min(const Vector2 &a, const Vector2 &b)
  584. {
  585. return Vector2(min(a.x, b.x), min(a.y, b.y));
  586. }
  587. static Vector2 max(const Vector2 &a, const Vector2 &b)
  588. {
  589. return Vector2(max(a.x, b.x), max(a.y, b.y));
  590. }
  591. static bool isFinite(const Vector2 &v)
  592. {
  593. return isFinite(v.x) && isFinite(v.y);
  594. }
  595. static float triangleArea(const Vector2 &a, const Vector2 &b, const Vector2 &c)
  596. {
  597. // IC: While it may be appealing to use the following expression:
  598. //return (c.x * a.y + a.x * b.y + b.x * c.y - b.x * a.y - c.x * b.y - a.x * c.y) * 0.5f;
  599. // That's actually a terrible idea. Small triangles far from the origin can end up producing fairly large floating point
  600. // numbers and the results becomes very unstable and dependent on the order of the factors.
  601. // Instead, it's preferable to subtract the vertices first, and multiply the resulting small values together. The result
  602. // in this case is always much more accurate (as long as the triangle is small) and less dependent of the location of
  603. // the triangle.
  604. //return ((a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x)) * 0.5f;
  605. const Vector2 v0 = a - c;
  606. const Vector2 v1 = b - c;
  607. return (v0.x * v1.y - v0.y * v1.x) * 0.5f;
  608. }
  609. static bool linesIntersect(const Vector2 &a1, const Vector2 &a2, const Vector2 &b1, const Vector2 &b2, float epsilon)
  610. {
  611. const Vector2 v0 = a2 - a1;
  612. const Vector2 v1 = b2 - b1;
  613. const float denom = -v1.x * v0.y + v0.x * v1.y;
  614. if (equal(denom, 0.0f, epsilon))
  615. return false;
  616. const float s = (-v0.y * (a1.x - b1.x) + v0.x * (a1.y - b1.y)) / denom;
  617. if (s > epsilon && s < 1.0f - epsilon) {
  618. const float t = ( v1.x * (a1.y - b1.y) - v1.y * (a1.x - b1.x)) / denom;
  619. return t > epsilon && t < 1.0f - epsilon;
  620. }
  621. return false;
  622. }
  623. struct Vector2i
  624. {
  625. Vector2i() {}
  626. Vector2i(int32_t _x, int32_t _y) : x(_x), y(_y) {}
  627. int32_t x, y;
  628. };
  629. class Vector3
  630. {
  631. public:
  632. Vector3() {}
  633. explicit Vector3(float f) : x(f), y(f), z(f) {}
  634. Vector3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {}
  635. Vector3(const Vector2 &v, float _z) : x(v.x), y(v.y), z(_z) {}
  636. Vector2 xy() const
  637. {
  638. return Vector2(x, y);
  639. }
  640. Vector3 operator-() const
  641. {
  642. return Vector3(-x, -y, -z);
  643. }
  644. void operator+=(const Vector3 &v)
  645. {
  646. x += v.x;
  647. y += v.y;
  648. z += v.z;
  649. }
  650. void operator-=(const Vector3 &v)
  651. {
  652. x -= v.x;
  653. y -= v.y;
  654. z -= v.z;
  655. }
  656. void operator*=(float s)
  657. {
  658. x *= s;
  659. y *= s;
  660. z *= s;
  661. }
  662. void operator/=(float s)
  663. {
  664. float is = 1.0f / s;
  665. x *= is;
  666. y *= is;
  667. z *= is;
  668. }
  669. void operator*=(const Vector3 &v)
  670. {
  671. x *= v.x;
  672. y *= v.y;
  673. z *= v.z;
  674. }
  675. void operator/=(const Vector3 &v)
  676. {
  677. x /= v.x;
  678. y /= v.y;
  679. z /= v.z;
  680. }
  681. float x, y, z;
  682. };
  683. static Vector3 operator+(const Vector3 &a, const Vector3 &b)
  684. {
  685. return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
  686. }
  687. static Vector3 operator-(const Vector3 &a, const Vector3 &b)
  688. {
  689. return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
  690. }
  691. static bool operator==(const Vector3 &a, const Vector3 &b)
  692. {
  693. return a.x == b.x && a.y == b.y && a.z == b.z;
  694. }
  695. static Vector3 cross(const Vector3 &a, const Vector3 &b)
  696. {
  697. return Vector3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
  698. }
  699. static Vector3 operator*(const Vector3 &v, float s)
  700. {
  701. return Vector3(v.x * s, v.y * s, v.z * s);
  702. }
  703. static Vector3 operator/(const Vector3 &v, float s)
  704. {
  705. return v * (1.0f / s);
  706. }
  707. static float dot(const Vector3 &a, const Vector3 &b)
  708. {
  709. return a.x * b.x + a.y * b.y + a.z * b.z;
  710. }
  711. static float lengthSquared(const Vector3 &v)
  712. {
  713. return v.x * v.x + v.y * v.y + v.z * v.z;
  714. }
  715. static float length(const Vector3 &v)
  716. {
  717. return sqrtf(lengthSquared(v));
  718. }
  719. static bool isNormalized(const Vector3 &v, float epsilon = kNormalEpsilon)
  720. {
  721. return equal(length(v), 1.0f, epsilon);
  722. }
  723. static Vector3 normalize(const Vector3 &v)
  724. {
  725. const float l = length(v);
  726. XA_DEBUG_ASSERT(l > 0.0f); // Never negative.
  727. const Vector3 n = v * (1.0f / l);
  728. XA_DEBUG_ASSERT(isNormalized(n));
  729. return n;
  730. }
  731. static Vector3 normalizeSafe(const Vector3 &v, const Vector3 &fallback)
  732. {
  733. const float l = length(v);
  734. if (l > 0.0f) // Never negative.
  735. return v * (1.0f / l);
  736. return fallback;
  737. }
  738. static bool equal(const Vector3 &v0, const Vector3 &v1, float epsilon)
  739. {
  740. return fabs(v0.x - v1.x) <= epsilon && fabs(v0.y - v1.y) <= epsilon && fabs(v0.z - v1.z) <= epsilon;
  741. }
  742. static Vector3 min(const Vector3 &a, const Vector3 &b)
  743. {
  744. return Vector3(min(a.x, b.x), min(a.y, b.y), min(a.z, b.z));
  745. }
  746. static Vector3 max(const Vector3 &a, const Vector3 &b)
  747. {
  748. return Vector3(max(a.x, b.x), max(a.y, b.y), max(a.z, b.z));
  749. }
  750. #if XA_DEBUG
  751. bool isFinite(const Vector3 &v)
  752. {
  753. return isFinite(v.x) && isFinite(v.y) && isFinite(v.z);
  754. }
  755. #endif
  756. struct Extents2
  757. {
  758. Vector2 min, max;
  759. Extents2() {}
  760. Extents2(Vector2 p1, Vector2 p2)
  761. {
  762. min = xatlas::internal::min(p1, p2);
  763. max = xatlas::internal::max(p1, p2);
  764. }
  765. void reset()
  766. {
  767. min.x = min.y = FLT_MAX;
  768. max.x = max.y = -FLT_MAX;
  769. }
  770. void add(Vector2 p)
  771. {
  772. min = xatlas::internal::min(min, p);
  773. max = xatlas::internal::max(max, p);
  774. }
  775. Vector2 midpoint() const
  776. {
  777. return Vector2(min.x + (max.x - min.x) * 0.5f, min.y + (max.y - min.y) * 0.5f);
  778. }
  779. static bool intersect(const Extents2 &e1, const Extents2 &e2)
  780. {
  781. return e1.min.x <= e2.max.x && e1.max.x >= e2.min.x && e1.min.y <= e2.max.y && e1.max.y >= e2.min.y;
  782. }
  783. };
  784. // From Fast-BVH
  785. struct AABB
  786. {
  787. AABB() : min(FLT_MAX, FLT_MAX, FLT_MAX), max(-FLT_MAX, -FLT_MAX, -FLT_MAX) {}
  788. AABB(const Vector3 &_min, const Vector3 &_max) : min(_min), max(_max) { }
  789. AABB(const Vector3 &p, float radius = 0.0f) : min(p), max(p) { if (radius > 0.0f) expand(radius); }
  790. bool intersect(const AABB &other) const
  791. {
  792. return min.x <= other.max.x && max.x >= other.min.x && min.y <= other.max.y && max.y >= other.min.y && min.z <= other.max.z && max.z >= other.min.z;
  793. }
  794. void expandToInclude(const Vector3 &p)
  795. {
  796. min = internal::min(min, p);
  797. max = internal::max(max, p);
  798. }
  799. void expandToInclude(const AABB &aabb)
  800. {
  801. min = internal::min(min, aabb.min);
  802. max = internal::max(max, aabb.max);
  803. }
  804. void expand(float amount)
  805. {
  806. min -= Vector3(amount);
  807. max += Vector3(amount);
  808. }
  809. Vector3 centroid() const
  810. {
  811. return min + (max - min) * 0.5f;
  812. }
  813. uint32_t maxDimension() const
  814. {
  815. const Vector3 extent = max - min;
  816. uint32_t result = 0;
  817. if (extent.y > extent.x) {
  818. result = 1;
  819. if (extent.z > extent.y)
  820. result = 2;
  821. }
  822. else if(extent.z > extent.x)
  823. result = 2;
  824. return result;
  825. }
  826. Vector3 min, max;
  827. };
  828. struct ArrayBase
  829. {
  830. ArrayBase(uint32_t _elementSize, int memTag = MemTag::Default) : buffer(nullptr), elementSize(_elementSize), size(0), capacity(0)
  831. {
  832. #if XA_DEBUG_HEAP
  833. this->memTag = memTag;
  834. #else
  835. XA_UNUSED(memTag);
  836. #endif
  837. }
  838. ~ArrayBase()
  839. {
  840. XA_FREE(buffer);
  841. }
  842. XA_INLINE void clear()
  843. {
  844. size = 0;
  845. }
  846. void copyFrom(const uint8_t *data, uint32_t length)
  847. {
  848. XA_DEBUG_ASSERT(data);
  849. XA_DEBUG_ASSERT(length > 0);
  850. resize(length, true);
  851. if (buffer && data && length > 0)
  852. memcpy(buffer, data, length * elementSize);
  853. }
  854. void copyTo(ArrayBase &other) const
  855. {
  856. XA_DEBUG_ASSERT(elementSize == other.elementSize);
  857. XA_DEBUG_ASSERT(size > 0);
  858. other.resize(size, true);
  859. if (other.buffer && buffer && size > 0)
  860. memcpy(other.buffer, buffer, size * elementSize);
  861. }
  862. void destroy()
  863. {
  864. size = 0;
  865. XA_FREE(buffer);
  866. buffer = nullptr;
  867. capacity = 0;
  868. size = 0;
  869. }
  870. // Insert the given element at the given index shifting all the elements up.
  871. void insertAt(uint32_t index, const uint8_t *value)
  872. {
  873. XA_DEBUG_ASSERT(index >= 0 && index <= size);
  874. XA_DEBUG_ASSERT(value);
  875. resize(size + 1, false);
  876. XA_DEBUG_ASSERT(buffer);
  877. if (buffer && index < size - 1)
  878. memmove(buffer + elementSize * (index + 1), buffer + elementSize * index, elementSize * (size - 1 - index));
  879. if (buffer && value)
  880. memcpy(&buffer[index * elementSize], value, elementSize);
  881. }
  882. void moveTo(ArrayBase &other)
  883. {
  884. XA_DEBUG_ASSERT(elementSize == other.elementSize);
  885. other.destroy();
  886. other.buffer = buffer;
  887. other.elementSize = elementSize;
  888. other.size = size;
  889. other.capacity = capacity;
  890. #if XA_DEBUG_HEAP
  891. other.memTag = memTag;
  892. #endif
  893. buffer = nullptr;
  894. elementSize = size = capacity = 0;
  895. }
  896. void pop_back()
  897. {
  898. XA_DEBUG_ASSERT(size > 0);
  899. resize(size - 1, false);
  900. }
  901. void push_back(const uint8_t *value)
  902. {
  903. XA_DEBUG_ASSERT(value < buffer || value >= buffer + size);
  904. XA_DEBUG_ASSERT(value);
  905. resize(size + 1, false);
  906. XA_DEBUG_ASSERT(buffer);
  907. if (buffer && value)
  908. memcpy(&buffer[(size - 1) * elementSize], value, elementSize);
  909. }
  910. void push_back(const ArrayBase &other)
  911. {
  912. XA_DEBUG_ASSERT(elementSize == other.elementSize);
  913. if (other.size > 0) {
  914. const uint32_t oldSize = size;
  915. resize(size + other.size, false);
  916. XA_DEBUG_ASSERT(buffer);
  917. if (buffer)
  918. memcpy(buffer + oldSize * elementSize, other.buffer, other.size * other.elementSize);
  919. }
  920. }
  921. // Remove the element at the given index. This is an expensive operation!
  922. void removeAt(uint32_t index)
  923. {
  924. XA_DEBUG_ASSERT(index >= 0 && index < size);
  925. XA_DEBUG_ASSERT(buffer);
  926. if (buffer) {
  927. if (size > 1)
  928. memmove(buffer + elementSize * index, buffer + elementSize * (index + 1), elementSize * (size - 1 - index));
  929. if (size > 0)
  930. size--;
  931. }
  932. }
  933. // Element at index is swapped with the last element, then the array length is decremented.
  934. void removeAtFast(uint32_t index)
  935. {
  936. XA_DEBUG_ASSERT(index >= 0 && index < size);
  937. XA_DEBUG_ASSERT(buffer);
  938. if (buffer) {
  939. if (size > 1 && index != size - 1)
  940. memcpy(buffer + elementSize * index, buffer + elementSize * (size - 1), elementSize);
  941. if (size > 0)
  942. size--;
  943. }
  944. }
  945. void reserve(uint32_t desiredSize)
  946. {
  947. if (desiredSize > capacity)
  948. setArrayCapacity(desiredSize);
  949. }
  950. void resize(uint32_t newSize, bool exact)
  951. {
  952. size = newSize;
  953. if (size > capacity) {
  954. // First allocation is always exact. Otherwise, following allocations grow array to 150% of desired size.
  955. uint32_t newBufferSize;
  956. if (capacity == 0 || exact)
  957. newBufferSize = size;
  958. else
  959. newBufferSize = size + (size >> 2);
  960. setArrayCapacity(newBufferSize);
  961. }
  962. }
  963. void setArrayCapacity(uint32_t newCapacity)
  964. {
  965. XA_DEBUG_ASSERT(newCapacity >= size);
  966. if (newCapacity == 0) {
  967. // free the buffer.
  968. if (buffer != nullptr) {
  969. XA_FREE(buffer);
  970. buffer = nullptr;
  971. }
  972. } else {
  973. // realloc the buffer
  974. #if XA_DEBUG_HEAP
  975. buffer = XA_REALLOC_SIZE(memTag, buffer, newCapacity * elementSize);
  976. #else
  977. buffer = XA_REALLOC_SIZE(MemTag::Default, buffer, newCapacity * elementSize);
  978. #endif
  979. }
  980. capacity = newCapacity;
  981. }
  982. #if XA_DEBUG_HEAP
  983. void setMemTag(int _memTag)
  984. {
  985. this->memTag = _memTag;
  986. }
  987. #endif
  988. uint8_t *buffer;
  989. uint32_t elementSize;
  990. uint32_t size;
  991. uint32_t capacity;
  992. #if XA_DEBUG_HEAP
  993. int memTag;
  994. #endif
  995. };
  996. template<typename T>
  997. class Array
  998. {
  999. public:
  1000. Array(int memTag = MemTag::Default) : m_base(sizeof(T), memTag) {}
  1001. Array(const Array&) = delete;
  1002. Array &operator=(const Array &) = delete;
  1003. XA_INLINE const T &operator[](uint32_t index) const
  1004. {
  1005. XA_DEBUG_ASSERT(index < m_base.size);
  1006. XA_DEBUG_ASSERT(m_base.buffer);
  1007. return ((const T *)m_base.buffer)[index];
  1008. }
  1009. XA_INLINE T &operator[](uint32_t index)
  1010. {
  1011. XA_DEBUG_ASSERT(index < m_base.size);
  1012. XA_DEBUG_ASSERT(m_base.buffer);
  1013. return ((T *)m_base.buffer)[index];
  1014. }
  1015. XA_INLINE const T &back() const
  1016. {
  1017. XA_DEBUG_ASSERT(!isEmpty());
  1018. return ((const T *)m_base.buffer)[m_base.size - 1];
  1019. }
  1020. XA_INLINE T *begin() { return (T *)m_base.buffer; }
  1021. XA_INLINE void clear() { m_base.clear(); }
  1022. bool contains(const T &value) const
  1023. {
  1024. for (uint32_t i = 0; i < m_base.size; i++) {
  1025. if (((const T *)m_base.buffer)[i] == value)
  1026. return true;
  1027. }
  1028. return false;
  1029. }
  1030. void copyFrom(const T *data, uint32_t length) { m_base.copyFrom((const uint8_t *)data, length); }
  1031. void copyTo(Array &other) const { m_base.copyTo(other.m_base); }
  1032. XA_INLINE const T *data() const { return (const T *)m_base.buffer; }
  1033. XA_INLINE T *data() { return (T *)m_base.buffer; }
  1034. void destroy() { m_base.destroy(); }
  1035. XA_INLINE T *end() { return (T *)m_base.buffer + m_base.size; }
  1036. XA_INLINE bool isEmpty() const { return m_base.size == 0; }
  1037. void insertAt(uint32_t index, const T &value) { m_base.insertAt(index, (const uint8_t *)&value); }
  1038. void moveTo(Array &other) { m_base.moveTo(other.m_base); }
  1039. void push_back(const T &value) { m_base.push_back((const uint8_t *)&value); }
  1040. void push_back(const Array &other) { m_base.push_back(other.m_base); }
  1041. void pop_back() { m_base.pop_back(); }
  1042. void removeAt(uint32_t index) { m_base.removeAt(index); }
  1043. void removeAtFast(uint32_t index) { m_base.removeAtFast(index); }
  1044. void reserve(uint32_t desiredSize) { m_base.reserve(desiredSize); }
  1045. void resize(uint32_t newSize) { m_base.resize(newSize, true); }
  1046. void runCtors()
  1047. {
  1048. for (uint32_t i = 0; i < m_base.size; i++)
  1049. new (&((T *)m_base.buffer)[i]) T;
  1050. }
  1051. void runDtors()
  1052. {
  1053. for (uint32_t i = 0; i < m_base.size; i++)
  1054. ((T *)m_base.buffer)[i].~T();
  1055. }
  1056. void fill(const T &value)
  1057. {
  1058. auto buffer = (T *)m_base.buffer;
  1059. for (uint32_t i = 0; i < m_base.size; i++)
  1060. buffer[i] = value;
  1061. }
  1062. void fillBytes(uint8_t value)
  1063. {
  1064. if (m_base.buffer && m_base.size > 0)
  1065. memset(m_base.buffer, (int)value, m_base.size * m_base.elementSize);
  1066. }
  1067. #if XA_DEBUG_HEAP
  1068. void setMemTag(int memTag) { m_base.setMemTag(memTag); }
  1069. #endif
  1070. XA_INLINE uint32_t size() const { return m_base.size; }
  1071. XA_INLINE void zeroOutMemory()
  1072. {
  1073. if (m_base.buffer && m_base.size > 0)
  1074. memset(m_base.buffer, 0, m_base.elementSize * m_base.size);
  1075. }
  1076. private:
  1077. ArrayBase m_base;
  1078. };
  1079. template<typename T>
  1080. struct ArrayView
  1081. {
  1082. ArrayView() : data(nullptr), length(0) {}
  1083. ArrayView(Array<T> &a) : data(a.data()), length(a.size()) {}
  1084. ArrayView(T *_data, uint32_t _length) : data(_data), length(_length) {}
  1085. ArrayView &operator=(Array<T> &a) { data = a.data(); length = a.size(); return *this; }
  1086. XA_INLINE const T &operator[](uint32_t index) const { XA_DEBUG_ASSERT(index < length); return data[index]; }
  1087. XA_INLINE T &operator[](uint32_t index) { XA_DEBUG_ASSERT(index < length); return data[index]; }
  1088. T *data;
  1089. uint32_t length;
  1090. };
  1091. template<typename T>
  1092. struct ConstArrayView
  1093. {
  1094. ConstArrayView() : data(nullptr), length(0) {}
  1095. ConstArrayView(const Array<T> &a) : data(a.data()), length(a.size()) {}
  1096. ConstArrayView(ArrayView<T> av) : data(av.data), length(av.length) {}
  1097. ConstArrayView(const T *_data, uint32_t _length) : data(_data), length(_length) {}
  1098. ConstArrayView &operator=(const Array<T> &a) { data = a.data(); length = a.size(); return *this; }
  1099. XA_INLINE const T &operator[](uint32_t index) const { XA_DEBUG_ASSERT(index < length); return data[index]; }
  1100. const T *data;
  1101. uint32_t length;
  1102. };
  1103. /// Basis class to compute tangent space basis, ortogonalizations and to transform vectors from one space to another.
  1104. struct Basis
  1105. {
  1106. XA_NODISCARD static Vector3 computeTangent(const Vector3 &normal)
  1107. {
  1108. XA_ASSERT(isNormalized(normal));
  1109. // Choose minimum axis.
  1110. Vector3 tangent;
  1111. if (fabsf(normal.x) < fabsf(normal.y) && fabsf(normal.x) < fabsf(normal.z))
  1112. tangent = Vector3(1, 0, 0);
  1113. else if (fabsf(normal.y) < fabsf(normal.z))
  1114. tangent = Vector3(0, 1, 0);
  1115. else
  1116. tangent = Vector3(0, 0, 1);
  1117. // Ortogonalize
  1118. tangent -= normal * dot(normal, tangent);
  1119. tangent = normalize(tangent);
  1120. return tangent;
  1121. }
  1122. XA_NODISCARD static Vector3 computeBitangent(const Vector3 &normal, const Vector3 &tangent)
  1123. {
  1124. return cross(normal, tangent);
  1125. }
  1126. Vector3 tangent = Vector3(0.0f);
  1127. Vector3 bitangent = Vector3(0.0f);
  1128. Vector3 normal = Vector3(0.0f);
  1129. };
  1130. // Simple bit array.
  1131. class BitArray
  1132. {
  1133. public:
  1134. BitArray() : m_size(0) {}
  1135. BitArray(uint32_t sz)
  1136. {
  1137. resize(sz);
  1138. }
  1139. void resize(uint32_t new_size)
  1140. {
  1141. m_size = new_size;
  1142. m_wordArray.resize((m_size + 31) >> 5);
  1143. }
  1144. bool get(uint32_t index) const
  1145. {
  1146. XA_DEBUG_ASSERT(index < m_size);
  1147. return (m_wordArray[index >> 5] & (1 << (index & 31))) != 0;
  1148. }
  1149. void set(uint32_t index)
  1150. {
  1151. XA_DEBUG_ASSERT(index < m_size);
  1152. m_wordArray[index >> 5] |= (1 << (index & 31));
  1153. }
  1154. void unset(uint32_t index)
  1155. {
  1156. XA_DEBUG_ASSERT(index < m_size);
  1157. m_wordArray[index >> 5] &= ~(1 << (index & 31));
  1158. }
  1159. void zeroOutMemory()
  1160. {
  1161. m_wordArray.zeroOutMemory();
  1162. }
  1163. private:
  1164. uint32_t m_size; // Number of bits stored.
  1165. Array<uint32_t> m_wordArray;
  1166. };
  1167. class BitImage
  1168. {
  1169. public:
  1170. BitImage() : m_width(0), m_height(0), m_rowStride(0), m_data(MemTag::BitImage) {}
  1171. BitImage(uint32_t w, uint32_t h) : m_width(w), m_height(h), m_data(MemTag::BitImage)
  1172. {
  1173. m_rowStride = (m_width + 63) >> 6;
  1174. m_data.resize(m_rowStride * m_height);
  1175. m_data.zeroOutMemory();
  1176. }
  1177. BitImage(const BitImage &other) = delete;
  1178. BitImage &operator=(const BitImage &other) = delete;
  1179. uint32_t width() const { return m_width; }
  1180. uint32_t height() const { return m_height; }
  1181. void copyTo(BitImage &other)
  1182. {
  1183. other.m_width = m_width;
  1184. other.m_height = m_height;
  1185. other.m_rowStride = m_rowStride;
  1186. m_data.copyTo(other.m_data);
  1187. }
  1188. void resize(uint32_t w, uint32_t h, bool discard)
  1189. {
  1190. const uint32_t rowStride = (w + 63) >> 6;
  1191. if (discard) {
  1192. m_data.resize(rowStride * h);
  1193. m_data.zeroOutMemory();
  1194. } else {
  1195. Array<uint64_t> tmp;
  1196. tmp.resize(rowStride * h);
  1197. memset(tmp.data(), 0, tmp.size() * sizeof(uint64_t));
  1198. // If only height has changed, can copy all rows at once.
  1199. if (rowStride == m_rowStride) {
  1200. memcpy(tmp.data(), m_data.data(), m_rowStride * min(m_height, h) * sizeof(uint64_t));
  1201. } else if (m_width > 0 && m_height > 0) {
  1202. const uint32_t height = min(m_height, h);
  1203. for (uint32_t i = 0; i < height; i++)
  1204. memcpy(&tmp[i * rowStride], &m_data[i * m_rowStride], min(rowStride, m_rowStride) * sizeof(uint64_t));
  1205. }
  1206. tmp.moveTo(m_data);
  1207. }
  1208. m_width = w;
  1209. m_height = h;
  1210. m_rowStride = rowStride;
  1211. }
  1212. bool get(uint32_t x, uint32_t y) const
  1213. {
  1214. XA_DEBUG_ASSERT(x < m_width && y < m_height);
  1215. const uint32_t index = (x >> 6) + y * m_rowStride;
  1216. return (m_data[index] & (UINT64_C(1) << (uint64_t(x) & UINT64_C(63)))) != 0;
  1217. }
  1218. void set(uint32_t x, uint32_t y)
  1219. {
  1220. XA_DEBUG_ASSERT(x < m_width && y < m_height);
  1221. const uint32_t index = (x >> 6) + y * m_rowStride;
  1222. m_data[index] |= UINT64_C(1) << (uint64_t(x) & UINT64_C(63));
  1223. XA_DEBUG_ASSERT(get(x, y));
  1224. }
  1225. void zeroOutMemory()
  1226. {
  1227. m_data.zeroOutMemory();
  1228. }
  1229. bool canBlit(const BitImage &image, uint32_t offsetX, uint32_t offsetY) const
  1230. {
  1231. for (uint32_t y = 0; y < image.m_height; y++) {
  1232. const uint32_t thisY = y + offsetY;
  1233. if (thisY >= m_height)
  1234. continue;
  1235. uint32_t x = 0;
  1236. for (;;) {
  1237. const uint32_t thisX = x + offsetX;
  1238. if (thisX >= m_width)
  1239. break;
  1240. const uint32_t thisBlockShift = thisX % 64;
  1241. const uint64_t thisBlock = m_data[(thisX >> 6) + thisY * m_rowStride] >> thisBlockShift;
  1242. const uint32_t blockShift = x % 64;
  1243. const uint64_t block = image.m_data[(x >> 6) + y * image.m_rowStride] >> blockShift;
  1244. if ((thisBlock & block) != 0)
  1245. return false;
  1246. x += 64 - max(thisBlockShift, blockShift);
  1247. if (x >= image.m_width)
  1248. break;
  1249. }
  1250. }
  1251. return true;
  1252. }
  1253. void dilate(uint32_t padding)
  1254. {
  1255. BitImage tmp(m_width, m_height);
  1256. for (uint32_t p = 0; p < padding; p++) {
  1257. tmp.zeroOutMemory();
  1258. for (uint32_t y = 0; y < m_height; y++) {
  1259. for (uint32_t x = 0; x < m_width; x++) {
  1260. bool b = get(x, y);
  1261. if (!b) {
  1262. if (x > 0) {
  1263. b |= get(x - 1, y);
  1264. if (y > 0) b |= get(x - 1, y - 1);
  1265. if (y < m_height - 1) b |= get(x - 1, y + 1);
  1266. }
  1267. if (y > 0) b |= get(x, y - 1);
  1268. if (y < m_height - 1) b |= get(x, y + 1);
  1269. if (x < m_width - 1) {
  1270. b |= get(x + 1, y);
  1271. if (y > 0) b |= get(x + 1, y - 1);
  1272. if (y < m_height - 1) b |= get(x + 1, y + 1);
  1273. }
  1274. }
  1275. if (b)
  1276. tmp.set(x, y);
  1277. }
  1278. }
  1279. tmp.m_data.copyTo(m_data);
  1280. }
  1281. }
  1282. private:
  1283. uint32_t m_width;
  1284. uint32_t m_height;
  1285. uint32_t m_rowStride; // In uint64_t's
  1286. Array<uint64_t> m_data;
  1287. };
  1288. // From Fast-BVH
  1289. class BVH
  1290. {
  1291. public:
  1292. BVH(const Array<AABB> &objectAabbs, uint32_t leafSize = 4) : m_objectIds(MemTag::BVH), m_nodes(MemTag::BVH)
  1293. {
  1294. m_objectAabbs = &objectAabbs;
  1295. if (m_objectAabbs->isEmpty())
  1296. return;
  1297. m_objectIds.resize(objectAabbs.size());
  1298. for (uint32_t i = 0; i < m_objectIds.size(); i++)
  1299. m_objectIds[i] = i;
  1300. BuildEntry todo[128];
  1301. uint32_t stackptr = 0;
  1302. const uint32_t kRoot = 0xfffffffc;
  1303. const uint32_t kUntouched = 0xffffffff;
  1304. const uint32_t kTouchedTwice = 0xfffffffd;
  1305. // Push the root
  1306. todo[stackptr].start = 0;
  1307. todo[stackptr].end = objectAabbs.size();
  1308. todo[stackptr].parent = kRoot;
  1309. stackptr++;
  1310. Node node;
  1311. m_nodes.reserve(objectAabbs.size() * 2);
  1312. uint32_t nNodes = 0;
  1313. while(stackptr > 0) {
  1314. // Pop the next item off of the stack
  1315. const BuildEntry &bnode = todo[--stackptr];
  1316. const uint32_t start = bnode.start;
  1317. const uint32_t end = bnode.end;
  1318. const uint32_t nPrims = end - start;
  1319. nNodes++;
  1320. node.start = start;
  1321. node.nPrims = nPrims;
  1322. node.rightOffset = kUntouched;
  1323. // Calculate the bounding box for this node
  1324. AABB bb(objectAabbs[m_objectIds[start]]);
  1325. AABB bc(objectAabbs[m_objectIds[start]].centroid());
  1326. for(uint32_t p = start + 1; p < end; ++p) {
  1327. bb.expandToInclude(objectAabbs[m_objectIds[p]]);
  1328. bc.expandToInclude(objectAabbs[m_objectIds[p]].centroid());
  1329. }
  1330. node.aabb = bb;
  1331. // If the number of primitives at this point is less than the leaf
  1332. // size, then this will become a leaf. (Signified by rightOffset == 0)
  1333. if (nPrims <= leafSize)
  1334. node.rightOffset = 0;
  1335. m_nodes.push_back(node);
  1336. // Child touches parent...
  1337. // Special case: Don't do this for the root.
  1338. if (bnode.parent != kRoot) {
  1339. m_nodes[bnode.parent].rightOffset--;
  1340. // When this is the second touch, this is the right child.
  1341. // The right child sets up the offset for the flat tree.
  1342. if (m_nodes[bnode.parent].rightOffset == kTouchedTwice )
  1343. m_nodes[bnode.parent].rightOffset = nNodes - 1 - bnode.parent;
  1344. }
  1345. // If this is a leaf, no need to subdivide.
  1346. if (node.rightOffset == 0)
  1347. continue;
  1348. // Set the split dimensions
  1349. const uint32_t split_dim = bc.maxDimension();
  1350. // Split on the center of the longest axis
  1351. const float split_coord = 0.5f * ((&bc.min.x)[split_dim] + (&bc.max.x)[split_dim]);
  1352. // Partition the list of objects on this split
  1353. uint32_t mid = start;
  1354. for (uint32_t i = start; i < end; ++i) {
  1355. const Vector3 centroid(objectAabbs[m_objectIds[i]].centroid());
  1356. if ((&centroid.x)[split_dim] < split_coord) {
  1357. swap(m_objectIds[i], m_objectIds[mid]);
  1358. ++mid;
  1359. }
  1360. }
  1361. // If we get a bad split, just choose the center...
  1362. if (mid == start || mid == end)
  1363. mid = start + (end - start) / 2;
  1364. // Push right child
  1365. todo[stackptr].start = mid;
  1366. todo[stackptr].end = end;
  1367. todo[stackptr].parent = nNodes - 1;
  1368. stackptr++;
  1369. // Push left child
  1370. todo[stackptr].start = start;
  1371. todo[stackptr].end = mid;
  1372. todo[stackptr].parent = nNodes - 1;
  1373. stackptr++;
  1374. }
  1375. }
  1376. void query(const AABB &queryAabb, Array<uint32_t> &result) const
  1377. {
  1378. result.clear();
  1379. // Working set
  1380. uint32_t todo[64];
  1381. int32_t stackptr = 0;
  1382. // "Push" on the root node to the working set
  1383. todo[stackptr] = 0;
  1384. while(stackptr >= 0) {
  1385. // Pop off the next node to work on.
  1386. const int ni = todo[stackptr--];
  1387. const Node &node = m_nodes[ni];
  1388. // Is leaf -> Intersect
  1389. if (node.rightOffset == 0) {
  1390. for(uint32_t o = 0; o < node.nPrims; ++o) {
  1391. const uint32_t obj = node.start + o;
  1392. if (queryAabb.intersect((*m_objectAabbs)[m_objectIds[obj]]))
  1393. result.push_back(m_objectIds[obj]);
  1394. }
  1395. } else { // Not a leaf
  1396. const uint32_t left = ni + 1;
  1397. const uint32_t right = ni + node.rightOffset;
  1398. if (queryAabb.intersect(m_nodes[left].aabb))
  1399. todo[++stackptr] = left;
  1400. if (queryAabb.intersect(m_nodes[right].aabb))
  1401. todo[++stackptr] = right;
  1402. }
  1403. }
  1404. }
  1405. private:
  1406. struct BuildEntry
  1407. {
  1408. uint32_t parent; // If non-zero then this is the index of the parent. (used in offsets)
  1409. uint32_t start, end; // The range of objects in the object list covered by this node.
  1410. };
  1411. struct Node
  1412. {
  1413. AABB aabb;
  1414. uint32_t start, nPrims, rightOffset;
  1415. };
  1416. const Array<AABB> *m_objectAabbs;
  1417. Array<uint32_t> m_objectIds;
  1418. Array<Node> m_nodes;
  1419. };
  1420. struct Fit
  1421. {
  1422. static bool computeBasis(ConstArrayView<Vector3> points, Basis *basis)
  1423. {
  1424. if (computeLeastSquaresNormal(points, &basis->normal)) {
  1425. basis->tangent = Basis::computeTangent(basis->normal);
  1426. basis->bitangent = Basis::computeBitangent(basis->normal, basis->tangent);
  1427. return true;
  1428. }
  1429. return computeEigen(points, basis);
  1430. }
  1431. private:
  1432. // Fit a plane to a collection of points.
  1433. // Fast, and accurate to within a few degrees.
  1434. // Returns None if the points do not span a plane.
  1435. // https://www.ilikebigbits.com/2015_03_04_plane_from_points.html
  1436. static bool computeLeastSquaresNormal(ConstArrayView<Vector3> points, Vector3 *normal)
  1437. {
  1438. XA_DEBUG_ASSERT(points.length >= 3);
  1439. if (points.length == 3) {
  1440. *normal = normalize(cross(points[2] - points[0], points[1] - points[0]));
  1441. return true;
  1442. }
  1443. const float invN = 1.0f / float(points.length);
  1444. Vector3 centroid(0.0f);
  1445. for (uint32_t i = 0; i < points.length; i++)
  1446. centroid += points[i];
  1447. centroid *= invN;
  1448. // Calculate full 3x3 covariance matrix, excluding symmetries:
  1449. float xx = 0.0f, xy = 0.0f, xz = 0.0f, yy = 0.0f, yz = 0.0f, zz = 0.0f;
  1450. for (uint32_t i = 0; i < points.length; i++) {
  1451. Vector3 r = points[i] - centroid;
  1452. xx += r.x * r.x;
  1453. xy += r.x * r.y;
  1454. xz += r.x * r.z;
  1455. yy += r.y * r.y;
  1456. yz += r.y * r.z;
  1457. zz += r.z * r.z;
  1458. }
  1459. #if 0
  1460. xx *= invN;
  1461. xy *= invN;
  1462. xz *= invN;
  1463. yy *= invN;
  1464. yz *= invN;
  1465. zz *= invN;
  1466. Vector3 weighted_dir(0.0f);
  1467. {
  1468. float det_x = yy * zz - yz * yz;
  1469. const Vector3 axis_dir(det_x, xz * yz - xy * zz, xy * yz - xz * yy);
  1470. float weight = det_x * det_x;
  1471. if (dot(weighted_dir, axis_dir) < 0.0f)
  1472. weight = -weight;
  1473. weighted_dir += axis_dir * weight;
  1474. }
  1475. {
  1476. float det_y = xx * zz - xz * xz;
  1477. const Vector3 axis_dir(xz * yz - xy * zz, det_y, xy * xz - yz * xx);
  1478. float weight = det_y * det_y;
  1479. if (dot(weighted_dir, axis_dir) < 0.0f)
  1480. weight = -weight;
  1481. weighted_dir += axis_dir * weight;
  1482. }
  1483. {
  1484. float det_z = xx * yy - xy * xy;
  1485. const Vector3 axis_dir(xy * yz - xz * yy, xy * xz - yz * xx, det_z);
  1486. float weight = det_z * det_z;
  1487. if (dot(weighted_dir, axis_dir) < 0.0f)
  1488. weight = -weight;
  1489. weighted_dir += axis_dir * weight;
  1490. }
  1491. *normal = normalize(weighted_dir, kEpsilon);
  1492. #else
  1493. const float det_x = yy * zz - yz * yz;
  1494. const float det_y = xx * zz - xz * xz;
  1495. const float det_z = xx * yy - xy * xy;
  1496. const float det_max = max(det_x, max(det_y, det_z));
  1497. if (det_max <= 0.0f)
  1498. return false; // The points don't span a plane
  1499. // Pick path with best conditioning:
  1500. Vector3 dir(0.0f);
  1501. if (det_max == det_x)
  1502. dir = Vector3(det_x,xz * yz - xy * zz,xy * yz - xz * yy);
  1503. else if (det_max == det_y)
  1504. dir = Vector3(xz * yz - xy * zz, det_y, xy * xz - yz * xx);
  1505. else if (det_max == det_z)
  1506. dir = Vector3(xy * yz - xz * yy, xy * xz - yz * xx, det_z);
  1507. const float len = length(dir);
  1508. if (isZero(len, kEpsilon))
  1509. return false;
  1510. *normal = dir * (1.0f / len);
  1511. #endif
  1512. return isNormalized(*normal);
  1513. }
  1514. static bool computeEigen(ConstArrayView<Vector3> points, Basis *basis)
  1515. {
  1516. float matrix[6];
  1517. computeCovariance(points, matrix);
  1518. if (matrix[0] == 0 && matrix[3] == 0 && matrix[5] == 0)
  1519. return false;
  1520. float eigenValues[3];
  1521. Vector3 eigenVectors[3];
  1522. if (!eigenSolveSymmetric3(matrix, eigenValues, eigenVectors))
  1523. return false;
  1524. basis->normal = normalize(eigenVectors[2]);
  1525. basis->tangent = normalize(eigenVectors[0]);
  1526. basis->bitangent = normalize(eigenVectors[1]);
  1527. return true;
  1528. }
  1529. static Vector3 computeCentroid(ConstArrayView<Vector3> points)
  1530. {
  1531. Vector3 centroid(0.0f);
  1532. for (uint32_t i = 0; i < points.length; i++)
  1533. centroid += points[i];
  1534. centroid /= float(points.length);
  1535. return centroid;
  1536. }
  1537. static Vector3 computeCovariance(ConstArrayView<Vector3> points, float * covariance)
  1538. {
  1539. // compute the centroid
  1540. Vector3 centroid = computeCentroid(points);
  1541. // compute covariance matrix
  1542. for (int i = 0; i < 6; i++) {
  1543. covariance[i] = 0.0f;
  1544. }
  1545. for (uint32_t i = 0; i < points.length; i++) {
  1546. Vector3 v = points[i] - centroid;
  1547. covariance[0] += v.x * v.x;
  1548. covariance[1] += v.x * v.y;
  1549. covariance[2] += v.x * v.z;
  1550. covariance[3] += v.y * v.y;
  1551. covariance[4] += v.y * v.z;
  1552. covariance[5] += v.z * v.z;
  1553. }
  1554. return centroid;
  1555. }
  1556. // Tridiagonal solver from Charles Bloom.
  1557. // Householder transforms followed by QL decomposition.
  1558. // Seems to be based on the code from Numerical Recipes in C.
  1559. static bool eigenSolveSymmetric3(const float matrix[6], float eigenValues[3], Vector3 eigenVectors[3])
  1560. {
  1561. XA_DEBUG_ASSERT(matrix != nullptr && eigenValues != nullptr && eigenVectors != nullptr);
  1562. float subd[3];
  1563. float diag[3];
  1564. float work[3][3];
  1565. work[0][0] = matrix[0];
  1566. work[0][1] = work[1][0] = matrix[1];
  1567. work[0][2] = work[2][0] = matrix[2];
  1568. work[1][1] = matrix[3];
  1569. work[1][2] = work[2][1] = matrix[4];
  1570. work[2][2] = matrix[5];
  1571. EigenSolver3_Tridiagonal(work, diag, subd);
  1572. if (!EigenSolver3_QLAlgorithm(work, diag, subd)) {
  1573. for (int i = 0; i < 3; i++) {
  1574. eigenValues[i] = 0;
  1575. eigenVectors[i] = Vector3(0);
  1576. }
  1577. return false;
  1578. }
  1579. for (int i = 0; i < 3; i++) {
  1580. eigenValues[i] = (float)diag[i];
  1581. }
  1582. // eigenvectors are the columns; make them the rows :
  1583. for (int i = 0; i < 3; i++) {
  1584. for (int j = 0; j < 3; j++) {
  1585. (&eigenVectors[j].x)[i] = (float) work[i][j];
  1586. }
  1587. }
  1588. // shuffle to sort by singular value :
  1589. if (eigenValues[2] > eigenValues[0] && eigenValues[2] > eigenValues[1]) {
  1590. swap(eigenValues[0], eigenValues[2]);
  1591. swap(eigenVectors[0], eigenVectors[2]);
  1592. }
  1593. if (eigenValues[1] > eigenValues[0]) {
  1594. swap(eigenValues[0], eigenValues[1]);
  1595. swap(eigenVectors[0], eigenVectors[1]);
  1596. }
  1597. if (eigenValues[2] > eigenValues[1]) {
  1598. swap(eigenValues[1], eigenValues[2]);
  1599. swap(eigenVectors[1], eigenVectors[2]);
  1600. }
  1601. XA_DEBUG_ASSERT(eigenValues[0] >= eigenValues[1] && eigenValues[0] >= eigenValues[2]);
  1602. XA_DEBUG_ASSERT(eigenValues[1] >= eigenValues[2]);
  1603. return true;
  1604. }
  1605. private:
  1606. static void EigenSolver3_Tridiagonal(float mat[3][3], float *diag, float *subd)
  1607. {
  1608. // Householder reduction T = Q^t M Q
  1609. // Input:
  1610. // mat, symmetric 3x3 matrix M
  1611. // Output:
  1612. // mat, orthogonal matrix Q
  1613. // diag, diagonal entries of T
  1614. // subd, subdiagonal entries of T (T is symmetric)
  1615. const float epsilon = 1e-08f;
  1616. float a = mat[0][0];
  1617. float b = mat[0][1];
  1618. float c = mat[0][2];
  1619. float d = mat[1][1];
  1620. float e = mat[1][2];
  1621. float f = mat[2][2];
  1622. diag[0] = a;
  1623. subd[2] = 0.f;
  1624. if (fabsf(c) >= epsilon) {
  1625. const float ell = sqrtf(b * b + c * c);
  1626. b /= ell;
  1627. c /= ell;
  1628. const float q = 2 * b * e + c * (f - d);
  1629. diag[1] = d + c * q;
  1630. diag[2] = f - c * q;
  1631. subd[0] = ell;
  1632. subd[1] = e - b * q;
  1633. mat[0][0] = 1;
  1634. mat[0][1] = 0;
  1635. mat[0][2] = 0;
  1636. mat[1][0] = 0;
  1637. mat[1][1] = b;
  1638. mat[1][2] = c;
  1639. mat[2][0] = 0;
  1640. mat[2][1] = c;
  1641. mat[2][2] = -b;
  1642. } else {
  1643. diag[1] = d;
  1644. diag[2] = f;
  1645. subd[0] = b;
  1646. subd[1] = e;
  1647. mat[0][0] = 1;
  1648. mat[0][1] = 0;
  1649. mat[0][2] = 0;
  1650. mat[1][0] = 0;
  1651. mat[1][1] = 1;
  1652. mat[1][2] = 0;
  1653. mat[2][0] = 0;
  1654. mat[2][1] = 0;
  1655. mat[2][2] = 1;
  1656. }
  1657. }
  1658. static bool EigenSolver3_QLAlgorithm(float mat[3][3], float *diag, float *subd)
  1659. {
  1660. // QL iteration with implicit shifting to reduce matrix from tridiagonal
  1661. // to diagonal
  1662. const int maxiter = 32;
  1663. for (int ell = 0; ell < 3; ell++) {
  1664. int iter;
  1665. for (iter = 0; iter < maxiter; iter++) {
  1666. int m;
  1667. for (m = ell; m <= 1; m++) {
  1668. float dd = fabsf(diag[m]) + fabsf(diag[m + 1]);
  1669. if ( fabsf(subd[m]) + dd == dd )
  1670. break;
  1671. }
  1672. if ( m == ell )
  1673. break;
  1674. float g = (diag[ell + 1] - diag[ell]) / (2 * subd[ell]);
  1675. float r = sqrtf(g * g + 1);
  1676. if ( g < 0 )
  1677. g = diag[m] - diag[ell] + subd[ell] / (g - r);
  1678. else
  1679. g = diag[m] - diag[ell] + subd[ell] / (g + r);
  1680. float s = 1, c = 1, p = 0;
  1681. for (int i = m - 1; i >= ell; i--) {
  1682. float f = s * subd[i], b = c * subd[i];
  1683. if ( fabsf(f) >= fabsf(g) ) {
  1684. c = g / f;
  1685. r = sqrtf(c * c + 1);
  1686. subd[i + 1] = f * r;
  1687. c *= (s = 1 / r);
  1688. } else {
  1689. s = f / g;
  1690. r = sqrtf(s * s + 1);
  1691. subd[i + 1] = g * r;
  1692. s *= (c = 1 / r);
  1693. }
  1694. g = diag[i + 1] - p;
  1695. r = (diag[i] - g) * s + 2 * b * c;
  1696. p = s * r;
  1697. diag[i + 1] = g + p;
  1698. g = c * r - b;
  1699. for (int k = 0; k < 3; k++) {
  1700. f = mat[k][i + 1];
  1701. mat[k][i + 1] = s * mat[k][i] + c * f;
  1702. mat[k][i] = c * mat[k][i] - s * f;
  1703. }
  1704. }
  1705. diag[ell] -= p;
  1706. subd[ell] = g;
  1707. subd[m] = 0;
  1708. }
  1709. if ( iter == maxiter )
  1710. // should not get here under normal circumstances
  1711. return false;
  1712. }
  1713. return true;
  1714. }
  1715. };
  1716. static uint32_t sdbmHash(const void *data_in, uint32_t size, uint32_t h = 5381)
  1717. {
  1718. const uint8_t *data = (const uint8_t *) data_in;
  1719. uint32_t i = 0;
  1720. while (i < size) {
  1721. h = (h << 16) + (h << 6) - h + (uint32_t ) data[i++];
  1722. }
  1723. return h;
  1724. }
  1725. template <typename T>
  1726. static uint32_t hash(const T &t, uint32_t h = 5381)
  1727. {
  1728. return sdbmHash(&t, sizeof(T), h);
  1729. }
  1730. template <typename Key>
  1731. struct Hash
  1732. {
  1733. uint32_t operator()(const Key &k) const { return hash(k); }
  1734. };
  1735. template <typename Key>
  1736. struct PassthroughHash
  1737. {
  1738. uint32_t operator()(const Key &k) const { return (uint32_t)k; }
  1739. };
  1740. template <typename Key>
  1741. struct Equal
  1742. {
  1743. bool operator()(const Key &k0, const Key &k1) const { return k0 == k1; }
  1744. };
  1745. template<typename Key, typename H = Hash<Key>, typename E = Equal<Key> >
  1746. class HashMap
  1747. {
  1748. public:
  1749. HashMap(int memTag, uint32_t size) : m_memTag(memTag), m_size(size), m_numSlots(0), m_slots(nullptr), m_keys(memTag), m_next(memTag)
  1750. {
  1751. }
  1752. ~HashMap()
  1753. {
  1754. if (m_slots)
  1755. XA_FREE(m_slots);
  1756. }
  1757. void destroy()
  1758. {
  1759. if (m_slots) {
  1760. XA_FREE(m_slots);
  1761. m_slots = nullptr;
  1762. }
  1763. m_keys.destroy();
  1764. m_next.destroy();
  1765. }
  1766. uint32_t add(const Key &key)
  1767. {
  1768. if (!m_slots)
  1769. alloc();
  1770. const uint32_t hash = computeHash(key);
  1771. m_keys.push_back(key);
  1772. m_next.push_back(m_slots[hash]);
  1773. m_slots[hash] = m_next.size() - 1;
  1774. return m_keys.size() - 1;
  1775. }
  1776. uint32_t get(const Key &key) const
  1777. {
  1778. if (!m_slots)
  1779. return UINT32_MAX;
  1780. return find(key, m_slots[computeHash(key)]);
  1781. }
  1782. uint32_t getNext(const Key &key, uint32_t current) const
  1783. {
  1784. return find(key, m_next[current]);
  1785. }
  1786. private:
  1787. void alloc()
  1788. {
  1789. XA_DEBUG_ASSERT(m_size > 0);
  1790. m_numSlots = nextPowerOfTwo(m_size);
  1791. auto minNumSlots = uint32_t(m_size * 1.3);
  1792. if (m_numSlots < minNumSlots)
  1793. m_numSlots = nextPowerOfTwo(minNumSlots);
  1794. m_slots = XA_ALLOC_ARRAY(m_memTag, uint32_t, m_numSlots);
  1795. for (uint32_t i = 0; i < m_numSlots; i++)
  1796. m_slots[i] = UINT32_MAX;
  1797. m_keys.reserve(m_size);
  1798. m_next.reserve(m_size);
  1799. }
  1800. uint32_t computeHash(const Key &key) const
  1801. {
  1802. H hash;
  1803. return hash(key) & (m_numSlots - 1);
  1804. }
  1805. uint32_t find(const Key &key, uint32_t current) const
  1806. {
  1807. E equal;
  1808. while (current != UINT32_MAX) {
  1809. if (equal(m_keys[current], key))
  1810. return current;
  1811. current = m_next[current];
  1812. }
  1813. return current;
  1814. }
  1815. int m_memTag;
  1816. uint32_t m_size;
  1817. uint32_t m_numSlots;
  1818. uint32_t *m_slots;
  1819. Array<Key> m_keys;
  1820. Array<uint32_t> m_next;
  1821. };
  1822. template<typename T>
  1823. static void insertionSort(T *data, uint32_t length)
  1824. {
  1825. for (int32_t i = 1; i < (int32_t)length; i++) {
  1826. T x = data[i];
  1827. int32_t j = i - 1;
  1828. while (j >= 0 && x < data[j]) {
  1829. data[j + 1] = data[j];
  1830. j--;
  1831. }
  1832. data[j + 1] = x;
  1833. }
  1834. }
  1835. class KISSRng
  1836. {
  1837. public:
  1838. KISSRng() { reset(); }
  1839. void reset()
  1840. {
  1841. x = 123456789;
  1842. y = 362436000;
  1843. z = 521288629;
  1844. c = 7654321;
  1845. }
  1846. uint32_t getRange(uint32_t range)
  1847. {
  1848. if (range == 0)
  1849. return 0;
  1850. x = 69069 * x + 12345;
  1851. y ^= (y << 13);
  1852. y ^= (y >> 17);
  1853. y ^= (y << 5);
  1854. uint64_t t = 698769069ULL * z + c;
  1855. c = (t >> 32);
  1856. return (x + y + (z = (uint32_t)t)) % (range + 1);
  1857. }
  1858. private:
  1859. uint32_t x, y, z, c;
  1860. };
  1861. // Based on Pierre Terdiman's and Michael Herf's source code.
  1862. // http://www.codercorner.com/RadixSortRevisited.htm
  1863. // http://www.stereopsis.com/radix.html
  1864. class RadixSort
  1865. {
  1866. public:
  1867. void sort(ConstArrayView<float> input)
  1868. {
  1869. if (input.length == 0) {
  1870. m_buffer1.clear();
  1871. m_buffer2.clear();
  1872. m_ranks = m_buffer1.data();
  1873. m_ranks2 = m_buffer2.data();
  1874. return;
  1875. }
  1876. // Resize lists if needed
  1877. m_buffer1.resize(input.length);
  1878. m_buffer2.resize(input.length);
  1879. m_ranks = m_buffer1.data();
  1880. m_ranks2 = m_buffer2.data();
  1881. m_validRanks = false;
  1882. if (input.length < 32)
  1883. insertionSort(input);
  1884. else {
  1885. // @@ Avoid touching the input multiple times.
  1886. for (uint32_t i = 0; i < input.length; i++) {
  1887. floatFlip((uint32_t &)input[i]);
  1888. }
  1889. radixSort(ConstArrayView<uint32_t>((const uint32_t *)input.data, input.length));
  1890. for (uint32_t i = 0; i < input.length; i++) {
  1891. ifloatFlip((uint32_t &)input[i]);
  1892. }
  1893. }
  1894. }
  1895. // Access to results. m_ranks is a list of indices in sorted order, i.e. in the order you may further process your data
  1896. const uint32_t *ranks() const
  1897. {
  1898. XA_DEBUG_ASSERT(m_validRanks);
  1899. return m_ranks;
  1900. }
  1901. private:
  1902. uint32_t *m_ranks, *m_ranks2;
  1903. Array<uint32_t> m_buffer1, m_buffer2;
  1904. bool m_validRanks = false;
  1905. void floatFlip(uint32_t &f)
  1906. {
  1907. int32_t mask = (int32_t(f) >> 31) | 0x80000000; // Warren Hunt, Manchor Ko.
  1908. f ^= mask;
  1909. }
  1910. void ifloatFlip(uint32_t &f)
  1911. {
  1912. uint32_t mask = ((f >> 31) - 1) | 0x80000000; // Michael Herf.
  1913. f ^= mask;
  1914. }
  1915. void createHistograms(ConstArrayView<uint32_t> input, uint32_t *histogram)
  1916. {
  1917. const uint32_t bucketCount = sizeof(uint32_t);
  1918. // Init bucket pointers.
  1919. uint32_t *h[bucketCount];
  1920. for (uint32_t i = 0; i < bucketCount; i++) {
  1921. h[i] = histogram + 256 * i;
  1922. }
  1923. // Clear histograms.
  1924. memset(histogram, 0, 256 * bucketCount * sizeof(uint32_t));
  1925. // @@ Add support for signed integers.
  1926. // Build histograms.
  1927. const uint8_t *p = (const uint8_t *)input.data; // @@ Does this break aliasing rules?
  1928. const uint8_t *pe = p + input.length * sizeof(uint32_t);
  1929. while (p != pe) {
  1930. h[0][*p++]++, h[1][*p++]++, h[2][*p++]++, h[3][*p++]++;
  1931. }
  1932. }
  1933. void insertionSort(ConstArrayView<float> input)
  1934. {
  1935. if (!m_validRanks) {
  1936. m_ranks[0] = 0;
  1937. for (uint32_t i = 1; i != input.length; ++i) {
  1938. int rank = m_ranks[i] = i;
  1939. uint32_t j = i;
  1940. while (j != 0 && input[rank] < input[m_ranks[j - 1]]) {
  1941. m_ranks[j] = m_ranks[j - 1];
  1942. --j;
  1943. }
  1944. if (i != j) {
  1945. m_ranks[j] = rank;
  1946. }
  1947. }
  1948. m_validRanks = true;
  1949. } else {
  1950. for (uint32_t i = 1; i != input.length; ++i) {
  1951. int rank = m_ranks[i];
  1952. uint32_t j = i;
  1953. while (j != 0 && input[rank] < input[m_ranks[j - 1]]) {
  1954. m_ranks[j] = m_ranks[j - 1];
  1955. --j;
  1956. }
  1957. if (i != j) {
  1958. m_ranks[j] = rank;
  1959. }
  1960. }
  1961. }
  1962. }
  1963. void radixSort(ConstArrayView<uint32_t> input)
  1964. {
  1965. const uint32_t P = sizeof(uint32_t); // pass count
  1966. // Allocate histograms & offsets on the stack
  1967. uint32_t histogram[256 * P];
  1968. uint32_t *link[256];
  1969. createHistograms(input, histogram);
  1970. // Radix sort, j is the pass number (0=LSB, P=MSB)
  1971. for (uint32_t j = 0; j < P; j++) {
  1972. // Pointer to this bucket.
  1973. const uint32_t *h = &histogram[j * 256];
  1974. auto inputBytes = (const uint8_t *)input.data; // @@ Is this aliasing legal?
  1975. inputBytes += j;
  1976. if (h[inputBytes[0]] == input.length) {
  1977. // Skip this pass, all values are the same.
  1978. continue;
  1979. }
  1980. // Create offsets
  1981. link[0] = m_ranks2;
  1982. for (uint32_t i = 1; i < 256; i++) link[i] = link[i - 1] + h[i - 1];
  1983. // Perform Radix Sort
  1984. if (!m_validRanks) {
  1985. for (uint32_t i = 0; i < input.length; i++) {
  1986. *link[inputBytes[i * P]]++ = i;
  1987. }
  1988. m_validRanks = true;
  1989. } else {
  1990. for (uint32_t i = 0; i < input.length; i++) {
  1991. const uint32_t idx = m_ranks[i];
  1992. *link[inputBytes[idx * P]]++ = idx;
  1993. }
  1994. }
  1995. // Swap pointers for next pass. Valid indices - the most recent ones - are in m_ranks after the swap.
  1996. swap(m_ranks, m_ranks2);
  1997. }
  1998. // All values were equal, generate linear ranks.
  1999. if (!m_validRanks) {
  2000. for (uint32_t i = 0; i < input.length; i++)
  2001. m_ranks[i] = i;
  2002. m_validRanks = true;
  2003. }
  2004. }
  2005. };
  2006. // Wrapping this in a class allows temporary arrays to be re-used.
  2007. class BoundingBox2D
  2008. {
  2009. public:
  2010. Vector2 majorAxis, minorAxis, minCorner, maxCorner;
  2011. void clear()
  2012. {
  2013. m_boundaryVertices.clear();
  2014. }
  2015. void appendBoundaryVertex(Vector2 v)
  2016. {
  2017. m_boundaryVertices.push_back(v);
  2018. }
  2019. // This should compute convex hull and use rotating calipers to find the best box. Currently it uses a brute force method.
  2020. // If vertices are empty, the boundary vertices are used.
  2021. void compute(ConstArrayView<Vector2> vertices = ConstArrayView<Vector2>())
  2022. {
  2023. XA_DEBUG_ASSERT(!m_boundaryVertices.isEmpty());
  2024. if (vertices.length == 0)
  2025. vertices = m_boundaryVertices;
  2026. convexHull(m_boundaryVertices, m_hull, 0.00001f);
  2027. // @@ Ideally I should use rotating calipers to find the best box. Using brute force for now.
  2028. float best_area = FLT_MAX;
  2029. Vector2 best_min(0);
  2030. Vector2 best_max(0);
  2031. Vector2 best_axis(0);
  2032. const uint32_t hullCount = m_hull.size();
  2033. for (uint32_t i = 0, j = hullCount - 1; i < hullCount; j = i, i++) {
  2034. if (equal(m_hull[i], m_hull[j], kEpsilon))
  2035. continue;
  2036. Vector2 axis = normalize(m_hull[i] - m_hull[j]);
  2037. XA_DEBUG_ASSERT(isFinite(axis));
  2038. // Compute bounding box.
  2039. Vector2 box_min(FLT_MAX, FLT_MAX);
  2040. Vector2 box_max(-FLT_MAX, -FLT_MAX);
  2041. // Consider all points, not only boundary points, in case the input chart is malformed.
  2042. for (uint32_t v = 0; v < vertices.length; v++) {
  2043. const Vector2 &point = vertices[v];
  2044. const float x = dot(axis, point);
  2045. const float y = dot(Vector2(-axis.y, axis.x), point);
  2046. box_min.x = min(box_min.x, x);
  2047. box_max.x = max(box_max.x, x);
  2048. box_min.y = min(box_min.y, y);
  2049. box_max.y = max(box_max.y, y);
  2050. }
  2051. // Compute box area.
  2052. const float area = (box_max.x - box_min.x) * (box_max.y - box_min.y);
  2053. if (area < best_area) {
  2054. best_area = area;
  2055. best_min = box_min;
  2056. best_max = box_max;
  2057. best_axis = axis;
  2058. }
  2059. }
  2060. majorAxis = best_axis;
  2061. minorAxis = Vector2(-best_axis.y, best_axis.x);
  2062. minCorner = best_min;
  2063. maxCorner = best_max;
  2064. XA_ASSERT(isFinite(majorAxis) && isFinite(minorAxis) && isFinite(minCorner));
  2065. }
  2066. private:
  2067. // Compute the convex hull using Graham Scan.
  2068. void convexHull(ConstArrayView<Vector2> input, Array<Vector2> &output, float epsilon)
  2069. {
  2070. m_coords.resize(input.length);
  2071. for (uint32_t i = 0; i < input.length; i++)
  2072. m_coords[i] = input[i].x;
  2073. m_radix.sort(m_coords);
  2074. const uint32_t *ranks = m_radix.ranks();
  2075. m_top.clear();
  2076. m_bottom.clear();
  2077. m_top.reserve(input.length);
  2078. m_bottom.reserve(input.length);
  2079. Vector2 P = input[ranks[0]];
  2080. Vector2 Q = input[ranks[input.length - 1]];
  2081. float topy = max(P.y, Q.y);
  2082. float boty = min(P.y, Q.y);
  2083. for (uint32_t i = 0; i < input.length; i++) {
  2084. Vector2 p = input[ranks[i]];
  2085. if (p.y >= boty)
  2086. m_top.push_back(p);
  2087. }
  2088. for (uint32_t i = 0; i < input.length; i++) {
  2089. Vector2 p = input[ranks[input.length - 1 - i]];
  2090. if (p.y <= topy)
  2091. m_bottom.push_back(p);
  2092. }
  2093. // Filter top list.
  2094. output.clear();
  2095. XA_DEBUG_ASSERT(m_top.size() >= 2);
  2096. output.push_back(m_top[0]);
  2097. output.push_back(m_top[1]);
  2098. for (uint32_t i = 2; i < m_top.size(); ) {
  2099. Vector2 a = output[output.size() - 2];
  2100. Vector2 b = output[output.size() - 1];
  2101. Vector2 c = m_top[i];
  2102. float area = triangleArea(a, b, c);
  2103. if (area >= -epsilon)
  2104. output.pop_back();
  2105. if (area < -epsilon || output.size() == 1) {
  2106. output.push_back(c);
  2107. i++;
  2108. }
  2109. }
  2110. uint32_t top_count = output.size();
  2111. XA_DEBUG_ASSERT(m_bottom.size() >= 2);
  2112. output.push_back(m_bottom[1]);
  2113. // Filter bottom list.
  2114. for (uint32_t i = 2; i < m_bottom.size(); ) {
  2115. Vector2 a = output[output.size() - 2];
  2116. Vector2 b = output[output.size() - 1];
  2117. Vector2 c = m_bottom[i];
  2118. float area = triangleArea(a, b, c);
  2119. if (area >= -epsilon)
  2120. output.pop_back();
  2121. if (area < -epsilon || output.size() == top_count) {
  2122. output.push_back(c);
  2123. i++;
  2124. }
  2125. }
  2126. // Remove duplicate element.
  2127. XA_DEBUG_ASSERT(output.size() > 0);
  2128. output.pop_back();
  2129. }
  2130. Array<Vector2> m_boundaryVertices;
  2131. Array<float> m_coords;
  2132. Array<Vector2> m_top, m_bottom, m_hull;
  2133. RadixSort m_radix;
  2134. };
  2135. struct EdgeKey
  2136. {
  2137. EdgeKey(const EdgeKey &k) : v0(k.v0), v1(k.v1) {}
  2138. EdgeKey(uint32_t _v0, uint32_t _v1) : v0(_v0), v1(_v1) {}
  2139. bool operator==(const EdgeKey &k) const { return v0 == k.v0 && v1 == k.v1; }
  2140. uint32_t v0;
  2141. uint32_t v1;
  2142. };
  2143. struct EdgeHash
  2144. {
  2145. uint32_t operator()(const EdgeKey &k) const { return k.v0 * 32768u + k.v1; }
  2146. };
  2147. static uint32_t meshEdgeFace(uint32_t edge) { return edge / 3; }
  2148. static uint32_t meshEdgeIndex0(uint32_t edge) { return edge; }
  2149. static uint32_t meshEdgeIndex1(uint32_t edge)
  2150. {
  2151. const uint32_t faceFirstEdge = edge / 3 * 3;
  2152. return faceFirstEdge + (edge - faceFirstEdge + 1) % 3;
  2153. }
  2154. struct MeshFlags
  2155. {
  2156. enum
  2157. {
  2158. HasIgnoredFaces = 1<<0,
  2159. HasNormals = 1<<1,
  2160. HasMaterials = 1<<2
  2161. };
  2162. };
  2163. class Mesh
  2164. {
  2165. public:
  2166. Mesh(float epsilon, uint32_t approxVertexCount, uint32_t approxFaceCount, uint32_t flags = 0, uint32_t id = UINT32_MAX) : m_epsilon(epsilon), m_flags(flags), m_id(id), m_faceIgnore(MemTag::Mesh), m_faceMaterials(MemTag::Mesh), m_indices(MemTag::MeshIndices), m_positions(MemTag::MeshPositions), m_normals(MemTag::MeshNormals), m_texcoords(MemTag::MeshTexcoords), m_nextColocalVertex(MemTag::MeshColocals), m_firstColocalVertex(MemTag::MeshColocals), m_boundaryEdges(MemTag::MeshBoundaries), m_oppositeEdges(MemTag::MeshBoundaries), m_edgeMap(MemTag::MeshEdgeMap, approxFaceCount * 3)
  2167. {
  2168. m_indices.reserve(approxFaceCount * 3);
  2169. m_positions.reserve(approxVertexCount);
  2170. m_texcoords.reserve(approxVertexCount);
  2171. if (m_flags & MeshFlags::HasIgnoredFaces)
  2172. m_faceIgnore.reserve(approxFaceCount);
  2173. if (m_flags & MeshFlags::HasNormals)
  2174. m_normals.reserve(approxVertexCount);
  2175. if (m_flags & MeshFlags::HasMaterials)
  2176. m_faceMaterials.reserve(approxFaceCount);
  2177. }
  2178. uint32_t flags() const { return m_flags; }
  2179. uint32_t id() const { return m_id; }
  2180. void addVertex(const Vector3 &pos, const Vector3 &normal = Vector3(0.0f), const Vector2 &texcoord = Vector2(0.0f))
  2181. {
  2182. XA_DEBUG_ASSERT(isFinite(pos));
  2183. m_positions.push_back(pos);
  2184. if (m_flags & MeshFlags::HasNormals)
  2185. m_normals.push_back(normal);
  2186. m_texcoords.push_back(texcoord);
  2187. }
  2188. void addFace(const uint32_t *indices, bool ignore = false, uint32_t material = UINT32_MAX)
  2189. {
  2190. if (m_flags & MeshFlags::HasIgnoredFaces)
  2191. m_faceIgnore.push_back(ignore);
  2192. if (m_flags & MeshFlags::HasMaterials)
  2193. m_faceMaterials.push_back(material);
  2194. const uint32_t firstIndex = m_indices.size();
  2195. for (uint32_t i = 0; i < 3; i++)
  2196. m_indices.push_back(indices[i]);
  2197. for (uint32_t i = 0; i < 3; i++) {
  2198. const uint32_t vertex0 = m_indices[firstIndex + i];
  2199. const uint32_t vertex1 = m_indices[firstIndex + (i + 1) % 3];
  2200. m_edgeMap.add(EdgeKey(vertex0, vertex1));
  2201. }
  2202. }
  2203. void createColocalsBVH()
  2204. {
  2205. const uint32_t vertexCount = m_positions.size();
  2206. Array<AABB> aabbs(MemTag::BVH);
  2207. aabbs.resize(vertexCount);
  2208. for (uint32_t i = 0; i < m_positions.size(); i++)
  2209. aabbs[i] = AABB(m_positions[i], m_epsilon);
  2210. BVH bvh(aabbs);
  2211. Array<uint32_t> colocals(MemTag::MeshColocals);
  2212. Array<uint32_t> potential(MemTag::MeshColocals);
  2213. m_nextColocalVertex.resize(vertexCount);
  2214. m_nextColocalVertex.fillBytes(0xff);
  2215. m_firstColocalVertex.resize(vertexCount);
  2216. m_firstColocalVertex.fillBytes(0xff);
  2217. for (uint32_t i = 0; i < vertexCount; i++) {
  2218. if (m_nextColocalVertex[i] != UINT32_MAX)
  2219. continue; // Already linked.
  2220. // Find other vertices colocal to this one.
  2221. colocals.clear();
  2222. colocals.push_back(i); // Always add this vertex.
  2223. bvh.query(AABB(m_positions[i], m_epsilon), potential);
  2224. for (uint32_t j = 0; j < potential.size(); j++) {
  2225. const uint32_t otherVertex = potential[j];
  2226. if (otherVertex != i && equal(m_positions[i], m_positions[otherVertex], m_epsilon) && m_nextColocalVertex[otherVertex] == UINT32_MAX)
  2227. colocals.push_back(otherVertex);
  2228. }
  2229. if (colocals.size() == 1) {
  2230. // No colocals for this vertex.
  2231. m_nextColocalVertex[i] = i;
  2232. m_firstColocalVertex[i] = i;
  2233. continue;
  2234. }
  2235. // Link in ascending order.
  2236. insertionSort(colocals.data(), colocals.size());
  2237. for (uint32_t j = 0; j < colocals.size(); j++) {
  2238. m_nextColocalVertex[colocals[j]] = colocals[(j + 1) % colocals.size()];
  2239. m_firstColocalVertex[colocals[j]] = colocals[0];
  2240. }
  2241. XA_DEBUG_ASSERT(m_nextColocalVertex[i] != UINT32_MAX);
  2242. }
  2243. }
  2244. void createColocalsHash()
  2245. {
  2246. const uint32_t vertexCount = m_positions.size();
  2247. HashMap<Vector3> positionToVertexMap(MemTag::Default, vertexCount);
  2248. for (uint32_t i = 0; i < vertexCount; i++)
  2249. positionToVertexMap.add(m_positions[i]);
  2250. Array<uint32_t> colocals(MemTag::MeshColocals);
  2251. m_nextColocalVertex.resize(vertexCount);
  2252. m_nextColocalVertex.fillBytes(0xff);
  2253. m_firstColocalVertex.resize(vertexCount);
  2254. m_firstColocalVertex.fillBytes(0xff);
  2255. for (uint32_t i = 0; i < vertexCount; i++) {
  2256. if (m_nextColocalVertex[i] != UINT32_MAX)
  2257. continue; // Already linked.
  2258. // Find other vertices colocal to this one.
  2259. colocals.clear();
  2260. colocals.push_back(i); // Always add this vertex.
  2261. uint32_t otherVertex = positionToVertexMap.get(m_positions[i]);
  2262. while (otherVertex != UINT32_MAX) {
  2263. if (otherVertex != i && equal(m_positions[i], m_positions[otherVertex], m_epsilon) && m_nextColocalVertex[otherVertex] == UINT32_MAX)
  2264. colocals.push_back(otherVertex);
  2265. otherVertex = positionToVertexMap.getNext(m_positions[i], otherVertex);
  2266. }
  2267. if (colocals.size() == 1) {
  2268. // No colocals for this vertex.
  2269. m_nextColocalVertex[i] = i;
  2270. m_firstColocalVertex[i] = i;
  2271. continue;
  2272. }
  2273. // Link in ascending order.
  2274. insertionSort(colocals.data(), colocals.size());
  2275. for (uint32_t j = 0; j < colocals.size(); j++) {
  2276. m_nextColocalVertex[colocals[j]] = colocals[(j + 1) % colocals.size()];
  2277. m_firstColocalVertex[colocals[j]] = colocals[0];
  2278. }
  2279. XA_DEBUG_ASSERT(m_nextColocalVertex[i] != UINT32_MAX);
  2280. }
  2281. }
  2282. void createColocals()
  2283. {
  2284. if (m_epsilon <= FLT_EPSILON)
  2285. createColocalsHash();
  2286. else
  2287. createColocalsBVH();
  2288. }
  2289. void createBoundaries()
  2290. {
  2291. const uint32_t edgeCount = m_indices.size();
  2292. const uint32_t vertexCount = m_positions.size();
  2293. m_oppositeEdges.resize(edgeCount);
  2294. m_boundaryEdges.reserve(uint32_t(edgeCount * 0.1f));
  2295. m_isBoundaryVertex.resize(vertexCount);
  2296. m_isBoundaryVertex.zeroOutMemory();
  2297. for (uint32_t i = 0; i < edgeCount; i++)
  2298. m_oppositeEdges[i] = UINT32_MAX;
  2299. const uint32_t faceCount = m_indices.size() / 3;
  2300. for (uint32_t i = 0; i < faceCount; i++) {
  2301. if (isFaceIgnored(i))
  2302. continue;
  2303. for (uint32_t j = 0; j < 3; j++) {
  2304. const uint32_t edge = i * 3 + j;
  2305. const uint32_t vertex0 = m_indices[edge];
  2306. const uint32_t vertex1 = m_indices[i * 3 + (j + 1) % 3];
  2307. // If there is an edge with opposite winding to this one, the edge isn't on a boundary.
  2308. const uint32_t oppositeEdge = findEdge(vertex1, vertex0);
  2309. if (oppositeEdge != UINT32_MAX) {
  2310. m_oppositeEdges[edge] = oppositeEdge;
  2311. } else {
  2312. m_boundaryEdges.push_back(edge);
  2313. m_isBoundaryVertex.set(vertex0);
  2314. m_isBoundaryVertex.set(vertex1);
  2315. }
  2316. }
  2317. }
  2318. }
  2319. /// Find edge, test all colocals.
  2320. uint32_t findEdge(uint32_t vertex0, uint32_t vertex1) const
  2321. {
  2322. // Try to find exact vertex match first.
  2323. {
  2324. EdgeKey key(vertex0, vertex1);
  2325. uint32_t edge = m_edgeMap.get(key);
  2326. while (edge != UINT32_MAX) {
  2327. // Don't find edges of ignored faces.
  2328. if (!isFaceIgnored(meshEdgeFace(edge)))
  2329. return edge;
  2330. edge = m_edgeMap.getNext(key, edge);
  2331. }
  2332. }
  2333. // If colocals were created, try every permutation.
  2334. if (!m_nextColocalVertex.isEmpty()) {
  2335. uint32_t colocalVertex0 = vertex0;
  2336. for (;;) {
  2337. uint32_t colocalVertex1 = vertex1;
  2338. for (;;) {
  2339. EdgeKey key(colocalVertex0, colocalVertex1);
  2340. uint32_t edge = m_edgeMap.get(key);
  2341. while (edge != UINT32_MAX) {
  2342. // Don't find edges of ignored faces.
  2343. if (!isFaceIgnored(meshEdgeFace(edge)))
  2344. return edge;
  2345. edge = m_edgeMap.getNext(key, edge);
  2346. }
  2347. colocalVertex1 = m_nextColocalVertex[colocalVertex1];
  2348. if (colocalVertex1 == vertex1)
  2349. break; // Back to start.
  2350. }
  2351. colocalVertex0 = m_nextColocalVertex[colocalVertex0];
  2352. if (colocalVertex0 == vertex0)
  2353. break; // Back to start.
  2354. }
  2355. }
  2356. return UINT32_MAX;
  2357. }
  2358. // Edge map can be destroyed when no longer used to reduce memory usage. It's used by:
  2359. // * Mesh::createBoundaries()
  2360. // * Mesh::edgeMap() (used by MeshFaceGroups)
  2361. void destroyEdgeMap()
  2362. {
  2363. m_edgeMap.destroy();
  2364. }
  2365. #if XA_DEBUG_EXPORT_OBJ
  2366. void writeObjVertices(FILE *file) const
  2367. {
  2368. for (uint32_t i = 0; i < m_positions.size(); i++)
  2369. fprintf(file, "v %g %g %g\n", m_positions[i].x, m_positions[i].y, m_positions[i].z);
  2370. if (m_flags & MeshFlags::HasNormals) {
  2371. for (uint32_t i = 0; i < m_normals.size(); i++)
  2372. fprintf(file, "vn %g %g %g\n", m_normals[i].x, m_normals[i].y, m_normals[i].z);
  2373. }
  2374. for (uint32_t i = 0; i < m_texcoords.size(); i++)
  2375. fprintf(file, "vt %g %g\n", m_texcoords[i].x, m_texcoords[i].y);
  2376. }
  2377. void writeObjFace(FILE *file, uint32_t face, uint32_t offset = 0) const
  2378. {
  2379. fprintf(file, "f ");
  2380. for (uint32_t j = 0; j < 3; j++) {
  2381. const uint32_t index = m_indices[face * 3 + j] + 1 + offset; // 1-indexed
  2382. fprintf(file, "%d/%d/%d%c", index, index, index, j == 2 ? '\n' : ' ');
  2383. }
  2384. }
  2385. void writeObjBoundaryEges(FILE *file) const
  2386. {
  2387. if (m_oppositeEdges.isEmpty())
  2388. return; // Boundaries haven't been created.
  2389. fprintf(file, "o boundary_edges\n");
  2390. for (uint32_t i = 0; i < edgeCount(); i++) {
  2391. if (m_oppositeEdges[i] != UINT32_MAX)
  2392. continue;
  2393. fprintf(file, "l %d %d\n", m_indices[meshEdgeIndex0(i)] + 1, m_indices[meshEdgeIndex1(i)] + 1); // 1-indexed
  2394. }
  2395. }
  2396. void writeObjFile(const char *filename) const
  2397. {
  2398. FILE *file;
  2399. XA_FOPEN(file, filename, "w");
  2400. if (!file)
  2401. return;
  2402. writeObjVertices(file);
  2403. fprintf(file, "s off\n");
  2404. fprintf(file, "o object\n");
  2405. for (uint32_t i = 0; i < faceCount(); i++)
  2406. writeObjFace(file, i);
  2407. writeObjBoundaryEges(file);
  2408. fclose(file);
  2409. }
  2410. #endif
  2411. float computeSurfaceArea() const
  2412. {
  2413. float area = 0;
  2414. for (uint32_t f = 0; f < faceCount(); f++)
  2415. area += computeFaceArea(f);
  2416. XA_DEBUG_ASSERT(area >= 0);
  2417. return area;
  2418. }
  2419. // Returned value is always positive, even if some triangles are flipped.
  2420. float computeParametricArea() const
  2421. {
  2422. float area = 0;
  2423. for (uint32_t f = 0; f < faceCount(); f++)
  2424. area += fabsf(computeFaceParametricArea(f)); // May be negative, depends on texcoord winding.
  2425. return area;
  2426. }
  2427. float computeFaceArea(uint32_t face) const
  2428. {
  2429. const Vector3 &p0 = m_positions[m_indices[face * 3 + 0]];
  2430. const Vector3 &p1 = m_positions[m_indices[face * 3 + 1]];
  2431. const Vector3 &p2 = m_positions[m_indices[face * 3 + 2]];
  2432. return length(cross(p1 - p0, p2 - p0)) * 0.5f;
  2433. }
  2434. Vector3 computeFaceCentroid(uint32_t face) const
  2435. {
  2436. Vector3 sum(0.0f);
  2437. for (uint32_t i = 0; i < 3; i++)
  2438. sum += m_positions[m_indices[face * 3 + i]];
  2439. return sum / 3.0f;
  2440. }
  2441. // Average of the edge midpoints weighted by the edge length.
  2442. // I want a point inside the triangle, but closer to the cirumcenter.
  2443. Vector3 computeFaceCenter(uint32_t face) const
  2444. {
  2445. const Vector3 &p0 = m_positions[m_indices[face * 3 + 0]];
  2446. const Vector3 &p1 = m_positions[m_indices[face * 3 + 1]];
  2447. const Vector3 &p2 = m_positions[m_indices[face * 3 + 2]];
  2448. const float l0 = length(p1 - p0);
  2449. const float l1 = length(p2 - p1);
  2450. const float l2 = length(p0 - p2);
  2451. const Vector3 m0 = (p0 + p1) * l0 / (l0 + l1 + l2);
  2452. const Vector3 m1 = (p1 + p2) * l1 / (l0 + l1 + l2);
  2453. const Vector3 m2 = (p2 + p0) * l2 / (l0 + l1 + l2);
  2454. return m0 + m1 + m2;
  2455. }
  2456. Vector3 computeFaceNormal(uint32_t face) const
  2457. {
  2458. const Vector3 &p0 = m_positions[m_indices[face * 3 + 0]];
  2459. const Vector3 &p1 = m_positions[m_indices[face * 3 + 1]];
  2460. const Vector3 &p2 = m_positions[m_indices[face * 3 + 2]];
  2461. const Vector3 e0 = p2 - p0;
  2462. const Vector3 e1 = p1 - p0;
  2463. const Vector3 normalAreaScaled = cross(e0, e1);
  2464. return normalizeSafe(normalAreaScaled, Vector3(0, 0, 1));
  2465. }
  2466. float computeFaceParametricArea(uint32_t face) const
  2467. {
  2468. const Vector2 &t0 = m_texcoords[m_indices[face * 3 + 0]];
  2469. const Vector2 &t1 = m_texcoords[m_indices[face * 3 + 1]];
  2470. const Vector2 &t2 = m_texcoords[m_indices[face * 3 + 2]];
  2471. return triangleArea(t0, t1, t2);
  2472. }
  2473. // @@ This is not exactly accurate, we should compare the texture coordinates...
  2474. bool isSeam(uint32_t edge) const
  2475. {
  2476. const uint32_t oppositeEdge = m_oppositeEdges[edge];
  2477. if (oppositeEdge == UINT32_MAX)
  2478. return false; // boundary edge
  2479. const uint32_t e0 = meshEdgeIndex0(edge);
  2480. const uint32_t e1 = meshEdgeIndex1(edge);
  2481. const uint32_t oe0 = meshEdgeIndex0(oppositeEdge);
  2482. const uint32_t oe1 = meshEdgeIndex1(oppositeEdge);
  2483. return m_indices[e0] != m_indices[oe1] || m_indices[e1] != m_indices[oe0];
  2484. }
  2485. bool isTextureSeam(uint32_t edge) const
  2486. {
  2487. const uint32_t oppositeEdge = m_oppositeEdges[edge];
  2488. if (oppositeEdge == UINT32_MAX)
  2489. return false; // boundary edge
  2490. const uint32_t e0 = meshEdgeIndex0(edge);
  2491. const uint32_t e1 = meshEdgeIndex1(edge);
  2492. const uint32_t oe0 = meshEdgeIndex0(oppositeEdge);
  2493. const uint32_t oe1 = meshEdgeIndex1(oppositeEdge);
  2494. return m_texcoords[m_indices[e0]] != m_texcoords[m_indices[oe1]] || m_texcoords[m_indices[e1]] != m_texcoords[m_indices[oe0]];
  2495. }
  2496. uint32_t firstColocalVertex(uint32_t vertex) const
  2497. {
  2498. XA_DEBUG_ASSERT(m_firstColocalVertex.size() == m_positions.size());
  2499. return m_firstColocalVertex[vertex];
  2500. }
  2501. XA_INLINE float epsilon() const { return m_epsilon; }
  2502. XA_INLINE uint32_t edgeCount() const { return m_indices.size(); }
  2503. XA_INLINE uint32_t oppositeEdge(uint32_t edge) const { return m_oppositeEdges[edge]; }
  2504. XA_INLINE bool isBoundaryEdge(uint32_t edge) const { return m_oppositeEdges[edge] == UINT32_MAX; }
  2505. XA_INLINE const Array<uint32_t> &boundaryEdges() const { return m_boundaryEdges; }
  2506. XA_INLINE bool isBoundaryVertex(uint32_t vertex) const { return m_isBoundaryVertex.get(vertex); }
  2507. XA_INLINE uint32_t vertexCount() const { return m_positions.size(); }
  2508. XA_INLINE uint32_t vertexAt(uint32_t i) const { return m_indices[i]; }
  2509. XA_INLINE const Vector3 &position(uint32_t vertex) const { return m_positions[vertex]; }
  2510. XA_INLINE ConstArrayView<Vector3> positions() const { return m_positions; }
  2511. XA_INLINE const Vector3 &normal(uint32_t vertex) const { XA_DEBUG_ASSERT(m_flags & MeshFlags::HasNormals); return m_normals[vertex]; }
  2512. XA_INLINE const Vector2 &texcoord(uint32_t vertex) const { return m_texcoords[vertex]; }
  2513. XA_INLINE Vector2 &texcoord(uint32_t vertex) { return m_texcoords[vertex]; }
  2514. XA_INLINE const ConstArrayView<Vector2> texcoords() const { return m_texcoords; }
  2515. XA_INLINE ArrayView<Vector2> texcoords() { return m_texcoords; }
  2516. XA_INLINE uint32_t faceCount() const { return m_indices.size() / 3; }
  2517. XA_INLINE ConstArrayView<uint32_t> indices() const { return m_indices; }
  2518. XA_INLINE uint32_t indexCount() const { return m_indices.size(); }
  2519. XA_INLINE bool isFaceIgnored(uint32_t face) const { return (m_flags & MeshFlags::HasIgnoredFaces) && m_faceIgnore[face]; }
  2520. XA_INLINE uint32_t faceMaterial(uint32_t face) const { return (m_flags & MeshFlags::HasMaterials) ? m_faceMaterials[face] : UINT32_MAX; }
  2521. XA_INLINE const HashMap<EdgeKey, EdgeHash> &edgeMap() const { return m_edgeMap; }
  2522. private:
  2523. float m_epsilon;
  2524. uint32_t m_flags;
  2525. uint32_t m_id;
  2526. Array<bool> m_faceIgnore;
  2527. Array<uint32_t> m_faceMaterials;
  2528. Array<uint32_t> m_indices;
  2529. Array<Vector3> m_positions;
  2530. Array<Vector3> m_normals;
  2531. Array<Vector2> m_texcoords;
  2532. // Populated by createColocals
  2533. Array<uint32_t> m_nextColocalVertex; // In: vertex index. Out: the vertex index of the next colocal position.
  2534. Array<uint32_t> m_firstColocalVertex;
  2535. // Populated by createBoundaries
  2536. BitArray m_isBoundaryVertex;
  2537. Array<uint32_t> m_boundaryEdges;
  2538. Array<uint32_t> m_oppositeEdges; // In: edge index. Out: the index of the opposite edge (i.e. wound the opposite direction). UINT32_MAX if the input edge is a boundary edge.
  2539. HashMap<EdgeKey, EdgeHash> m_edgeMap;
  2540. public:
  2541. class FaceEdgeIterator
  2542. {
  2543. public:
  2544. FaceEdgeIterator (const Mesh *mesh, uint32_t face) : m_mesh(mesh), m_face(face), m_relativeEdge(0)
  2545. {
  2546. m_edge = m_face * 3;
  2547. }
  2548. void advance()
  2549. {
  2550. if (m_relativeEdge < 3) {
  2551. m_edge++;
  2552. m_relativeEdge++;
  2553. }
  2554. }
  2555. bool isDone() const
  2556. {
  2557. return m_relativeEdge == 3;
  2558. }
  2559. bool isBoundary() const { return m_mesh->m_oppositeEdges[m_edge] == UINT32_MAX; }
  2560. bool isSeam() const { return m_mesh->isSeam(m_edge); }
  2561. bool isTextureSeam() const { return m_mesh->isTextureSeam(m_edge); }
  2562. uint32_t edge() const { return m_edge; }
  2563. uint32_t relativeEdge() const { return m_relativeEdge; }
  2564. uint32_t face() const { return m_face; }
  2565. uint32_t oppositeEdge() const { return m_mesh->m_oppositeEdges[m_edge]; }
  2566. uint32_t oppositeFace() const
  2567. {
  2568. const uint32_t oedge = m_mesh->m_oppositeEdges[m_edge];
  2569. if (oedge == UINT32_MAX)
  2570. return UINT32_MAX;
  2571. return meshEdgeFace(oedge);
  2572. }
  2573. uint32_t vertex0() const { return m_mesh->m_indices[m_face * 3 + m_relativeEdge]; }
  2574. uint32_t vertex1() const { return m_mesh->m_indices[m_face * 3 + (m_relativeEdge + 1) % 3]; }
  2575. const Vector3 &position0() const { return m_mesh->m_positions[vertex0()]; }
  2576. const Vector3 &position1() const { return m_mesh->m_positions[vertex1()]; }
  2577. const Vector3 &normal0() const { return m_mesh->m_normals[vertex0()]; }
  2578. const Vector3 &normal1() const { return m_mesh->m_normals[vertex1()]; }
  2579. const Vector2 &texcoord0() const { return m_mesh->m_texcoords[vertex0()]; }
  2580. const Vector2 &texcoord1() const { return m_mesh->m_texcoords[vertex1()]; }
  2581. private:
  2582. const Mesh *m_mesh;
  2583. uint32_t m_face;
  2584. uint32_t m_edge;
  2585. uint32_t m_relativeEdge;
  2586. };
  2587. };
  2588. struct MeshFaceGroups
  2589. {
  2590. typedef uint32_t Handle;
  2591. static constexpr Handle kInvalid = UINT32_MAX;
  2592. MeshFaceGroups(const Mesh *mesh) : m_mesh(mesh), m_groups(MemTag::Mesh), m_firstFace(MemTag::Mesh), m_nextFace(MemTag::Mesh), m_faceCount(MemTag::Mesh) {}
  2593. XA_INLINE Handle groupAt(uint32_t face) const { return m_groups[face]; }
  2594. XA_INLINE uint32_t groupCount() const { return m_faceCount.size(); }
  2595. XA_INLINE uint32_t nextFace(uint32_t face) const { return m_nextFace[face]; }
  2596. XA_INLINE uint32_t faceCount(uint32_t group) const { return m_faceCount[group]; }
  2597. void compute()
  2598. {
  2599. m_groups.resize(m_mesh->faceCount());
  2600. m_groups.fillBytes(0xff); // Set all faces to kInvalid
  2601. uint32_t firstUnassignedFace = 0;
  2602. Handle group = 0;
  2603. Array<uint32_t> growFaces;
  2604. const uint32_t n = m_mesh->faceCount();
  2605. m_nextFace.resize(n);
  2606. for (;;) {
  2607. // Find an unassigned face.
  2608. uint32_t face = UINT32_MAX;
  2609. for (uint32_t f = firstUnassignedFace; f < n; f++) {
  2610. if (m_groups[f] == kInvalid && !m_mesh->isFaceIgnored(f)) {
  2611. face = f;
  2612. firstUnassignedFace = f + 1;
  2613. break;
  2614. }
  2615. }
  2616. if (face == UINT32_MAX)
  2617. break; // All faces assigned to a group (except ignored faces).
  2618. m_groups[face] = group;
  2619. m_nextFace[face] = UINT32_MAX;
  2620. m_firstFace.push_back(face);
  2621. growFaces.clear();
  2622. growFaces.push_back(face);
  2623. uint32_t prevFace = face, groupFaceCount = 1;
  2624. // Find faces connected to the face and assign them to the same group as the face, unless they are already assigned to another group.
  2625. for (;;) {
  2626. if (growFaces.isEmpty())
  2627. break;
  2628. const uint32_t f = growFaces.back();
  2629. growFaces.pop_back();
  2630. const uint32_t material = m_mesh->faceMaterial(f);
  2631. for (Mesh::FaceEdgeIterator edgeIt(m_mesh, f); !edgeIt.isDone(); edgeIt.advance()) {
  2632. const uint32_t oppositeEdge = m_mesh->findEdge(edgeIt.vertex1(), edgeIt.vertex0());
  2633. if (oppositeEdge == UINT32_MAX)
  2634. continue; // Boundary edge.
  2635. const uint32_t oppositeFace = meshEdgeFace(oppositeEdge);
  2636. if (m_mesh->isFaceIgnored(oppositeFace))
  2637. continue; // Don't add ignored faces to group.
  2638. if (m_mesh->faceMaterial(oppositeFace) != material)
  2639. continue; // Different material.
  2640. if (m_groups[oppositeFace] != kInvalid)
  2641. continue; // Connected face is already assigned to another group.
  2642. m_groups[oppositeFace] = group;
  2643. m_nextFace[oppositeFace] = UINT32_MAX;
  2644. if (prevFace != UINT32_MAX)
  2645. m_nextFace[prevFace] = oppositeFace;
  2646. prevFace = oppositeFace;
  2647. groupFaceCount++;
  2648. growFaces.push_back(oppositeFace);
  2649. }
  2650. }
  2651. m_faceCount.push_back(groupFaceCount);
  2652. group++;
  2653. XA_ASSERT(group < kInvalid);
  2654. }
  2655. }
  2656. class Iterator
  2657. {
  2658. public:
  2659. Iterator(const MeshFaceGroups *meshFaceGroups, Handle group) : m_meshFaceGroups(meshFaceGroups)
  2660. {
  2661. XA_DEBUG_ASSERT(group != kInvalid);
  2662. m_current = m_meshFaceGroups->m_firstFace[group];
  2663. }
  2664. void advance()
  2665. {
  2666. m_current = m_meshFaceGroups->m_nextFace[m_current];
  2667. }
  2668. bool isDone() const
  2669. {
  2670. return m_current == UINT32_MAX;
  2671. }
  2672. uint32_t face() const
  2673. {
  2674. return m_current;
  2675. }
  2676. private:
  2677. const MeshFaceGroups *m_meshFaceGroups;
  2678. uint32_t m_current;
  2679. };
  2680. private:
  2681. const Mesh *m_mesh;
  2682. Array<Handle> m_groups;
  2683. Array<uint32_t> m_firstFace;
  2684. Array<uint32_t> m_nextFace; // In: face. Out: the next face in the same group.
  2685. Array<uint32_t> m_faceCount; // In: face group. Out: number of faces in the group.
  2686. };
  2687. constexpr MeshFaceGroups::Handle MeshFaceGroups::kInvalid;
  2688. #if XA_CHECK_T_JUNCTIONS
  2689. static bool lineIntersectsPoint(const Vector3 &point, const Vector3 &lineStart, const Vector3 &lineEnd, float *t, float epsilon)
  2690. {
  2691. float tt;
  2692. if (!t)
  2693. t = &tt;
  2694. *t = 0.0f;
  2695. if (equal(lineStart, point, epsilon) || equal(lineEnd, point, epsilon))
  2696. return false; // Vertex lies on either line vertices.
  2697. const Vector3 v01 = point - lineStart;
  2698. const Vector3 v21 = lineEnd - lineStart;
  2699. const float l = length(v21);
  2700. const float d = length(cross(v01, v21)) / l;
  2701. if (!isZero(d, epsilon))
  2702. return false;
  2703. *t = dot(v01, v21) / (l * l);
  2704. return *t > kEpsilon && *t < 1.0f - kEpsilon;
  2705. }
  2706. // Returns the number of T-junctions found.
  2707. static int meshCheckTJunctions(const Mesh &inputMesh)
  2708. {
  2709. int count = 0;
  2710. const uint32_t vertexCount = inputMesh.vertexCount();
  2711. const uint32_t edgeCount = inputMesh.edgeCount();
  2712. for (uint32_t v = 0; v < vertexCount; v++) {
  2713. if (!inputMesh.isBoundaryVertex(v))
  2714. continue;
  2715. // Find edges that this vertex overlaps with.
  2716. const Vector3 &pos = inputMesh.position(v);
  2717. for (uint32_t e = 0; e < edgeCount; e++) {
  2718. if (!inputMesh.isBoundaryEdge(e))
  2719. continue;
  2720. const Vector3 &edgePos1 = inputMesh.position(inputMesh.vertexAt(meshEdgeIndex0(e)));
  2721. const Vector3 &edgePos2 = inputMesh.position(inputMesh.vertexAt(meshEdgeIndex1(e)));
  2722. float t;
  2723. if (lineIntersectsPoint(pos, edgePos1, edgePos2, &t, inputMesh.epsilon()))
  2724. count++;
  2725. }
  2726. }
  2727. return count;
  2728. }
  2729. #endif
  2730. // References invalid faces and vertices in a mesh.
  2731. struct InvalidMeshGeometry
  2732. {
  2733. // If meshFaceGroups is not null, invalid faces have the face group MeshFaceGroups::kInvalid.
  2734. // If meshFaceGroups is null, invalid faces are Mesh::isFaceIgnored.
  2735. void extract(const Mesh *mesh, const MeshFaceGroups *meshFaceGroups)
  2736. {
  2737. // Copy invalid faces.
  2738. m_faces.clear();
  2739. const uint32_t meshFaceCount = mesh->faceCount();
  2740. for (uint32_t f = 0; f < meshFaceCount; f++) {
  2741. if ((meshFaceGroups && meshFaceGroups->groupAt(f) == MeshFaceGroups::kInvalid) || (!meshFaceGroups && mesh->isFaceIgnored(f)))
  2742. m_faces.push_back(f);
  2743. }
  2744. // Create *unique* list of vertices of invalid faces.
  2745. const uint32_t faceCount = m_faces.size();
  2746. m_indices.resize(faceCount * 3);
  2747. const uint32_t approxVertexCount = min(faceCount * 3, mesh->vertexCount());
  2748. m_vertexToSourceVertexMap.clear();
  2749. m_vertexToSourceVertexMap.reserve(approxVertexCount);
  2750. HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToVertexMap(MemTag::Mesh, approxVertexCount);
  2751. for (uint32_t f = 0; f < faceCount; f++) {
  2752. const uint32_t face = m_faces[f];
  2753. for (uint32_t i = 0; i < 3; i++) {
  2754. const uint32_t vertex = mesh->vertexAt(face * 3 + i);
  2755. uint32_t newVertex = sourceVertexToVertexMap.get(vertex);
  2756. if (newVertex == UINT32_MAX) {
  2757. newVertex = sourceVertexToVertexMap.add(vertex);
  2758. m_vertexToSourceVertexMap.push_back(vertex);
  2759. }
  2760. m_indices[f * 3 + i] = newVertex;
  2761. }
  2762. }
  2763. }
  2764. ConstArrayView<uint32_t> faces() const { return m_faces; }
  2765. ConstArrayView<uint32_t> indices() const { return m_indices; }
  2766. ConstArrayView<uint32_t> vertices() const { return m_vertexToSourceVertexMap; }
  2767. private:
  2768. Array<uint32_t> m_faces, m_indices;
  2769. Array<uint32_t> m_vertexToSourceVertexMap; // Map face vertices to vertices of the source mesh.
  2770. };
  2771. struct Progress
  2772. {
  2773. Progress(ProgressCategory category, ProgressFunc func, void *userData, uint32_t maxValue) : cancel(false), m_category(category), m_func(func), m_userData(userData), m_value(0), m_maxValue(maxValue), m_percent(0)
  2774. {
  2775. if (m_func) {
  2776. if (!m_func(category, 0, userData))
  2777. cancel = true;
  2778. }
  2779. }
  2780. ~Progress()
  2781. {
  2782. if (m_func) {
  2783. if (!m_func(m_category, 100, m_userData))
  2784. cancel = true;
  2785. }
  2786. }
  2787. void increment(uint32_t value)
  2788. {
  2789. m_value += value;
  2790. update();
  2791. }
  2792. void setMaxValue(uint32_t maxValue)
  2793. {
  2794. m_maxValue = maxValue;
  2795. update();
  2796. }
  2797. std::atomic<bool> cancel;
  2798. private:
  2799. void update()
  2800. {
  2801. if (!m_func)
  2802. return;
  2803. const uint32_t newPercent = uint32_t(ceilf(m_value.load() / (float)m_maxValue.load() * 100.0f));
  2804. if (newPercent != m_percent) {
  2805. // Atomic max.
  2806. uint32_t oldPercent = m_percent;
  2807. while (oldPercent < newPercent && !m_percent.compare_exchange_weak(oldPercent, newPercent)) {}
  2808. if (!m_func(m_category, m_percent, m_userData))
  2809. cancel = true;
  2810. }
  2811. }
  2812. ProgressCategory m_category;
  2813. ProgressFunc m_func;
  2814. void *m_userData;
  2815. std::atomic<uint32_t> m_value, m_maxValue, m_percent;
  2816. };
  2817. struct Spinlock
  2818. {
  2819. void lock() { while(m_lock.test_and_set(std::memory_order_acquire)) {} }
  2820. void unlock() { m_lock.clear(std::memory_order_release); }
  2821. private:
  2822. std::atomic_flag m_lock = ATOMIC_FLAG_INIT;
  2823. };
  2824. struct TaskGroupHandle
  2825. {
  2826. uint32_t value = UINT32_MAX;
  2827. };
  2828. struct Task
  2829. {
  2830. void (*func)(void *groupUserData, void *taskUserData);
  2831. void *userData; // Passed to func as taskUserData.
  2832. };
  2833. #if XA_MULTITHREADED
  2834. class TaskScheduler
  2835. {
  2836. public:
  2837. TaskScheduler() : m_shutdown(false)
  2838. {
  2839. m_threadIndex = 0;
  2840. // Max with current task scheduler usage is 1 per thread + 1 deep nesting, but allow for some slop.
  2841. m_maxGroups = std::thread::hardware_concurrency() * 4;
  2842. m_groups = XA_ALLOC_ARRAY(MemTag::Default, TaskGroup, m_maxGroups);
  2843. for (uint32_t i = 0; i < m_maxGroups; i++) {
  2844. new (&m_groups[i]) TaskGroup();
  2845. m_groups[i].free = true;
  2846. m_groups[i].ref = 0;
  2847. m_groups[i].userData = nullptr;
  2848. }
  2849. m_workers.resize(std::thread::hardware_concurrency() <= 1 ? 1 : std::thread::hardware_concurrency() - 1);
  2850. for (uint32_t i = 0; i < m_workers.size(); i++) {
  2851. new (&m_workers[i]) Worker();
  2852. m_workers[i].wakeup = false;
  2853. m_workers[i].thread = XA_NEW_ARGS(MemTag::Default, std::thread, workerThread, this, &m_workers[i], i + 1);
  2854. }
  2855. }
  2856. ~TaskScheduler()
  2857. {
  2858. m_shutdown = true;
  2859. for (uint32_t i = 0; i < m_workers.size(); i++) {
  2860. Worker &worker = m_workers[i];
  2861. XA_DEBUG_ASSERT(worker.thread);
  2862. worker.wakeup = true;
  2863. worker.cv.notify_one();
  2864. if (worker.thread->joinable())
  2865. worker.thread->join();
  2866. worker.thread->~thread();
  2867. XA_FREE(worker.thread);
  2868. worker.~Worker();
  2869. }
  2870. for (uint32_t i = 0; i < m_maxGroups; i++)
  2871. m_groups[i].~TaskGroup();
  2872. XA_FREE(m_groups);
  2873. }
  2874. uint32_t threadCount() const
  2875. {
  2876. return max(1u, std::thread::hardware_concurrency()); // Including the main thread.
  2877. }
  2878. // userData is passed to Task::func as groupUserData.
  2879. TaskGroupHandle createTaskGroup(void *userData = nullptr, uint32_t reserveSize = 0)
  2880. {
  2881. // Claim the first free group.
  2882. for (uint32_t i = 0; i < m_maxGroups; i++) {
  2883. TaskGroup &group = m_groups[i];
  2884. bool expected = true;
  2885. if (!group.free.compare_exchange_strong(expected, false))
  2886. continue;
  2887. group.queueLock.lock();
  2888. group.queueHead = 0;
  2889. group.queue.clear();
  2890. group.queue.reserve(reserveSize);
  2891. group.queueLock.unlock();
  2892. group.userData = userData;
  2893. group.ref = 0;
  2894. TaskGroupHandle handle;
  2895. handle.value = i;
  2896. return handle;
  2897. }
  2898. XA_DEBUG_ASSERT(false);
  2899. TaskGroupHandle handle;
  2900. handle.value = UINT32_MAX;
  2901. return handle;
  2902. }
  2903. void run(TaskGroupHandle handle, const Task &task)
  2904. {
  2905. XA_DEBUG_ASSERT(handle.value != UINT32_MAX);
  2906. TaskGroup &group = m_groups[handle.value];
  2907. group.queueLock.lock();
  2908. group.queue.push_back(task);
  2909. group.queueLock.unlock();
  2910. group.ref++;
  2911. // Wake up a worker to run this task.
  2912. for (uint32_t i = 0; i < m_workers.size(); i++) {
  2913. m_workers[i].wakeup = true;
  2914. m_workers[i].cv.notify_one();
  2915. }
  2916. }
  2917. void wait(TaskGroupHandle *handle)
  2918. {
  2919. if (handle->value == UINT32_MAX) {
  2920. XA_DEBUG_ASSERT(false);
  2921. return;
  2922. }
  2923. // Run tasks from the group queue until empty.
  2924. TaskGroup &group = m_groups[handle->value];
  2925. for (;;) {
  2926. Task *task = nullptr;
  2927. group.queueLock.lock();
  2928. if (group.queueHead < group.queue.size())
  2929. task = &group.queue[group.queueHead++];
  2930. group.queueLock.unlock();
  2931. if (!task)
  2932. break;
  2933. task->func(group.userData, task->userData);
  2934. group.ref--;
  2935. }
  2936. // Even though the task queue is empty, workers can still be running tasks.
  2937. while (group.ref > 0)
  2938. std::this_thread::yield();
  2939. group.free = true;
  2940. handle->value = UINT32_MAX;
  2941. }
  2942. static uint32_t currentThreadIndex() { return m_threadIndex; }
  2943. private:
  2944. struct TaskGroup
  2945. {
  2946. std::atomic<bool> free;
  2947. Array<Task> queue; // Items are never removed. queueHead is incremented to pop items.
  2948. uint32_t queueHead = 0;
  2949. Spinlock queueLock;
  2950. std::atomic<uint32_t> ref; // Increment when a task is enqueued, decrement when a task finishes.
  2951. void *userData;
  2952. };
  2953. struct Worker
  2954. {
  2955. std::thread *thread = nullptr;
  2956. std::mutex mutex;
  2957. std::condition_variable cv;
  2958. std::atomic<bool> wakeup;
  2959. };
  2960. TaskGroup *m_groups;
  2961. Array<Worker> m_workers;
  2962. std::atomic<bool> m_shutdown;
  2963. uint32_t m_maxGroups;
  2964. static thread_local uint32_t m_threadIndex;
  2965. static void workerThread(TaskScheduler *scheduler, Worker *worker, uint32_t threadIndex)
  2966. {
  2967. m_threadIndex = threadIndex;
  2968. std::unique_lock<std::mutex> lock(worker->mutex);
  2969. for (;;) {
  2970. worker->cv.wait(lock, [=]{ return worker->wakeup.load(); });
  2971. worker->wakeup = false;
  2972. for (;;) {
  2973. if (scheduler->m_shutdown)
  2974. return;
  2975. // Look for a task in any of the groups and run it.
  2976. TaskGroup *group = nullptr;
  2977. Task *task = nullptr;
  2978. for (uint32_t i = 0; i < scheduler->m_maxGroups; i++) {
  2979. group = &scheduler->m_groups[i];
  2980. if (group->free || group->ref == 0)
  2981. continue;
  2982. group->queueLock.lock();
  2983. if (group->queueHead < group->queue.size()) {
  2984. task = &group->queue[group->queueHead++];
  2985. group->queueLock.unlock();
  2986. break;
  2987. }
  2988. group->queueLock.unlock();
  2989. }
  2990. if (!task)
  2991. break;
  2992. task->func(group->userData, task->userData);
  2993. group->ref--;
  2994. }
  2995. }
  2996. }
  2997. };
  2998. thread_local uint32_t TaskScheduler::m_threadIndex;
  2999. #else
  3000. class TaskScheduler
  3001. {
  3002. public:
  3003. ~TaskScheduler()
  3004. {
  3005. for (uint32_t i = 0; i < m_groups.size(); i++)
  3006. destroyGroup({ i });
  3007. }
  3008. uint32_t threadCount() const
  3009. {
  3010. return 1;
  3011. }
  3012. TaskGroupHandle createTaskGroup(void *userData = nullptr, uint32_t reserveSize = 0)
  3013. {
  3014. TaskGroup *group = XA_NEW(MemTag::Default, TaskGroup);
  3015. group->queue.reserve(reserveSize);
  3016. group->userData = userData;
  3017. m_groups.push_back(group);
  3018. TaskGroupHandle handle;
  3019. handle.value = m_groups.size() - 1;
  3020. return handle;
  3021. }
  3022. void run(TaskGroupHandle handle, Task task)
  3023. {
  3024. m_groups[handle.value]->queue.push_back(task);
  3025. }
  3026. void wait(TaskGroupHandle *handle)
  3027. {
  3028. if (handle->value == UINT32_MAX) {
  3029. XA_DEBUG_ASSERT(false);
  3030. return;
  3031. }
  3032. TaskGroup *group = m_groups[handle->value];
  3033. for (uint32_t i = 0; i < group->queue.size(); i++)
  3034. group->queue[i].func(group->userData, group->queue[i].userData);
  3035. group->queue.clear();
  3036. destroyGroup(*handle);
  3037. handle->value = UINT32_MAX;
  3038. }
  3039. static uint32_t currentThreadIndex() { return 0; }
  3040. private:
  3041. void destroyGroup(TaskGroupHandle handle)
  3042. {
  3043. TaskGroup *group = m_groups[handle.value];
  3044. if (group) {
  3045. group->~TaskGroup();
  3046. XA_FREE(group);
  3047. m_groups[handle.value] = nullptr;
  3048. }
  3049. }
  3050. struct TaskGroup
  3051. {
  3052. Array<Task> queue;
  3053. void *userData;
  3054. };
  3055. Array<TaskGroup *> m_groups;
  3056. };
  3057. #endif
  3058. #if XA_DEBUG_EXPORT_TGA
  3059. const uint8_t TGA_TYPE_RGB = 2;
  3060. const uint8_t TGA_ORIGIN_UPPER = 0x20;
  3061. #pragma pack(push, 1)
  3062. struct TgaHeader
  3063. {
  3064. uint8_t id_length;
  3065. uint8_t colormap_type;
  3066. uint8_t image_type;
  3067. uint16_t colormap_index;
  3068. uint16_t colormap_length;
  3069. uint8_t colormap_size;
  3070. uint16_t x_origin;
  3071. uint16_t y_origin;
  3072. uint16_t width;
  3073. uint16_t height;
  3074. uint8_t pixel_size;
  3075. uint8_t flags;
  3076. enum { Size = 18 };
  3077. };
  3078. #pragma pack(pop)
  3079. static void WriteTga(const char *filename, const uint8_t *data, uint32_t width, uint32_t height)
  3080. {
  3081. XA_DEBUG_ASSERT(sizeof(TgaHeader) == TgaHeader::Size);
  3082. FILE *f;
  3083. XA_FOPEN(f, filename, "wb");
  3084. if (!f)
  3085. return;
  3086. TgaHeader tga;
  3087. tga.id_length = 0;
  3088. tga.colormap_type = 0;
  3089. tga.image_type = TGA_TYPE_RGB;
  3090. tga.colormap_index = 0;
  3091. tga.colormap_length = 0;
  3092. tga.colormap_size = 0;
  3093. tga.x_origin = 0;
  3094. tga.y_origin = 0;
  3095. tga.width = (uint16_t)width;
  3096. tga.height = (uint16_t)height;
  3097. tga.pixel_size = 24;
  3098. tga.flags = TGA_ORIGIN_UPPER;
  3099. fwrite(&tga, sizeof(TgaHeader), 1, f);
  3100. fwrite(data, sizeof(uint8_t), width * height * 3, f);
  3101. fclose(f);
  3102. }
  3103. #endif
  3104. template<typename T>
  3105. class ThreadLocal
  3106. {
  3107. public:
  3108. ThreadLocal()
  3109. {
  3110. #if XA_MULTITHREADED
  3111. const uint32_t n = std::thread::hardware_concurrency();
  3112. #else
  3113. const uint32_t n = 1;
  3114. #endif
  3115. m_array = XA_ALLOC_ARRAY(MemTag::Default, T, n);
  3116. for (uint32_t i = 0; i < n; i++)
  3117. new (&m_array[i]) T;
  3118. }
  3119. ~ThreadLocal()
  3120. {
  3121. #if XA_MULTITHREADED
  3122. const uint32_t n = std::thread::hardware_concurrency();
  3123. #else
  3124. const uint32_t n = 1;
  3125. #endif
  3126. for (uint32_t i = 0; i < n; i++)
  3127. m_array[i].~T();
  3128. XA_FREE(m_array);
  3129. }
  3130. T &get() const
  3131. {
  3132. return m_array[TaskScheduler::currentThreadIndex()];
  3133. }
  3134. private:
  3135. T *m_array;
  3136. };
  3137. // Implemented as a struct so the temporary arrays can be reused.
  3138. struct Triangulator
  3139. {
  3140. // This is doing a simple ear-clipping algorithm that skips invalid triangles. Ideally, we should
  3141. // also sort the ears by angle, start with the ones that have the smallest angle and proceed in order.
  3142. void triangulatePolygon(ConstArrayView<Vector3> vertices, ConstArrayView<uint32_t> inputIndices, Array<uint32_t> &outputIndices)
  3143. {
  3144. m_polygonVertices.clear();
  3145. m_polygonVertices.reserve(inputIndices.length);
  3146. outputIndices.clear();
  3147. if (inputIndices.length == 3) {
  3148. // Simple case for triangles.
  3149. outputIndices.push_back(inputIndices[0]);
  3150. outputIndices.push_back(inputIndices[1]);
  3151. outputIndices.push_back(inputIndices[2]);
  3152. }
  3153. else {
  3154. // Build 2D polygon projecting vertices onto normal plane.
  3155. // Faces are not necesarily planar, this is for example the case, when the face comes from filling a hole. In such cases
  3156. // it's much better to use the best fit plane.
  3157. Basis basis;
  3158. basis.normal = normalize(cross(vertices[inputIndices[1]] - vertices[inputIndices[0]], vertices[inputIndices[2]] - vertices[inputIndices[1]]));
  3159. basis.tangent = basis.computeTangent(basis.normal);
  3160. basis.bitangent = basis.computeBitangent(basis.normal, basis.tangent);
  3161. const uint32_t edgeCount = inputIndices.length;
  3162. m_polygonPoints.clear();
  3163. m_polygonPoints.reserve(edgeCount);
  3164. m_polygonAngles.clear();
  3165. m_polygonAngles.reserve(edgeCount);
  3166. for (uint32_t i = 0; i < inputIndices.length; i++) {
  3167. m_polygonVertices.push_back(inputIndices[i]);
  3168. const Vector3 &pos = vertices[inputIndices[i]];
  3169. m_polygonPoints.push_back(Vector2(dot(basis.tangent, pos), dot(basis.bitangent, pos)));
  3170. }
  3171. m_polygonAngles.resize(edgeCount);
  3172. while (m_polygonVertices.size() > 2) {
  3173. const uint32_t size = m_polygonVertices.size();
  3174. // Update polygon angles. @@ Update only those that have changed.
  3175. float minAngle = kPi2;
  3176. uint32_t bestEar = 0; // Use first one if none of them is valid.
  3177. bool bestIsValid = false;
  3178. for (uint32_t i = 0; i < size; i++) {
  3179. uint32_t i0 = i;
  3180. uint32_t i1 = (i + 1) % size; // Use Sean's polygon interation trick.
  3181. uint32_t i2 = (i + 2) % size;
  3182. Vector2 p0 = m_polygonPoints[i0];
  3183. Vector2 p1 = m_polygonPoints[i1];
  3184. Vector2 p2 = m_polygonPoints[i2];
  3185. float d = clamp(dot(p0 - p1, p2 - p1) / (length(p0 - p1) * length(p2 - p1)), -1.0f, 1.0f);
  3186. float angle = acosf(d);
  3187. float area = triangleArea(p0, p1, p2);
  3188. if (area < 0.0f)
  3189. angle = kPi2 - angle;
  3190. m_polygonAngles[i1] = angle;
  3191. if (angle < minAngle || !bestIsValid) {
  3192. // Make sure this is a valid ear, if not, skip this point.
  3193. bool valid = true;
  3194. for (uint32_t j = 0; j < size; j++) {
  3195. if (j == i0 || j == i1 || j == i2)
  3196. continue;
  3197. Vector2 p = m_polygonPoints[j];
  3198. if (pointInTriangle(p, p0, p1, p2)) {
  3199. valid = false;
  3200. break;
  3201. }
  3202. }
  3203. if (valid || !bestIsValid) {
  3204. minAngle = angle;
  3205. bestEar = i1;
  3206. bestIsValid = valid;
  3207. }
  3208. }
  3209. }
  3210. // Clip best ear:
  3211. const uint32_t i0 = (bestEar + size - 1) % size;
  3212. const uint32_t i1 = (bestEar + 0) % size;
  3213. const uint32_t i2 = (bestEar + 1) % size;
  3214. outputIndices.push_back(m_polygonVertices[i0]);
  3215. outputIndices.push_back(m_polygonVertices[i1]);
  3216. outputIndices.push_back(m_polygonVertices[i2]);
  3217. m_polygonVertices.removeAt(i1);
  3218. m_polygonPoints.removeAt(i1);
  3219. m_polygonAngles.removeAt(i1);
  3220. }
  3221. }
  3222. }
  3223. private:
  3224. static bool pointInTriangle(const Vector2 &p, const Vector2 &a, const Vector2 &b, const Vector2 &c)
  3225. {
  3226. return triangleArea(a, b, p) >= kAreaEpsilon && triangleArea(b, c, p) >= kAreaEpsilon && triangleArea(c, a, p) >= kAreaEpsilon;
  3227. }
  3228. Array<int> m_polygonVertices;
  3229. Array<float> m_polygonAngles;
  3230. Array<Vector2> m_polygonPoints;
  3231. };
  3232. class UniformGrid2
  3233. {
  3234. public:
  3235. // indices are optional.
  3236. void reset(ConstArrayView<Vector2> positions, ConstArrayView<uint32_t> indices = ConstArrayView<uint32_t>(), uint32_t reserveEdgeCount = 0)
  3237. {
  3238. m_edges.clear();
  3239. if (reserveEdgeCount > 0)
  3240. m_edges.reserve(reserveEdgeCount);
  3241. m_positions = positions;
  3242. m_indices = indices;
  3243. m_cellDataOffsets.clear();
  3244. }
  3245. void append(uint32_t edge)
  3246. {
  3247. XA_DEBUG_ASSERT(m_cellDataOffsets.isEmpty());
  3248. m_edges.push_back(edge);
  3249. }
  3250. bool intersect(Vector2 v1, Vector2 v2, float epsilon)
  3251. {
  3252. const uint32_t edgeCount = m_edges.size();
  3253. bool bruteForce = edgeCount <= 20;
  3254. if (!bruteForce && m_cellDataOffsets.isEmpty())
  3255. bruteForce = !createGrid();
  3256. if (bruteForce) {
  3257. for (uint32_t j = 0; j < edgeCount; j++) {
  3258. const uint32_t edge = m_edges[j];
  3259. if (linesIntersect(v1, v2, edgePosition0(edge), edgePosition1(edge), epsilon))
  3260. return true;
  3261. }
  3262. } else {
  3263. computePotentialEdges(v1, v2);
  3264. uint32_t prevEdge = UINT32_MAX;
  3265. for (uint32_t j = 0; j < m_potentialEdges.size(); j++) {
  3266. const uint32_t edge = m_potentialEdges[j];
  3267. if (edge == prevEdge)
  3268. continue;
  3269. if (linesIntersect(v1, v2, edgePosition0(edge), edgePosition1(edge), epsilon))
  3270. return true;
  3271. prevEdge = edge;
  3272. }
  3273. }
  3274. return false;
  3275. }
  3276. // If edges is empty, checks for intersection with all edges in the grid.
  3277. bool intersect(float epsilon, ConstArrayView<uint32_t> edges = ConstArrayView<uint32_t>(), ConstArrayView<uint32_t> ignoreEdges = ConstArrayView<uint32_t>())
  3278. {
  3279. bool bruteForce = m_edges.size() <= 20;
  3280. if (!bruteForce && m_cellDataOffsets.isEmpty())
  3281. bruteForce = !createGrid();
  3282. const uint32_t *edges1, *edges2 = nullptr;
  3283. uint32_t edges1Count, edges2Count = 0;
  3284. if (edges.length == 0) {
  3285. edges1 = m_edges.data();
  3286. edges1Count = m_edges.size();
  3287. } else {
  3288. edges1 = edges.data;
  3289. edges1Count = edges.length;
  3290. }
  3291. if (bruteForce) {
  3292. edges2 = m_edges.data();
  3293. edges2Count = m_edges.size();
  3294. }
  3295. for (uint32_t i = 0; i < edges1Count; i++) {
  3296. const uint32_t edge1 = edges1[i];
  3297. const uint32_t edge1Vertex[2] = { vertexAt(meshEdgeIndex0(edge1)), vertexAt(meshEdgeIndex1(edge1)) };
  3298. const Vector2 &edge1Position1 = m_positions[edge1Vertex[0]];
  3299. const Vector2 &edge1Position2 = m_positions[edge1Vertex[1]];
  3300. const Extents2 edge1Extents(edge1Position1, edge1Position2);
  3301. uint32_t j = 0;
  3302. if (bruteForce) {
  3303. // If checking against self, test each edge pair only once.
  3304. if (edges.length == 0) {
  3305. j = i + 1;
  3306. if (j == edges1Count)
  3307. break;
  3308. }
  3309. } else {
  3310. computePotentialEdges(edgePosition0(edge1), edgePosition1(edge1));
  3311. edges2 = m_potentialEdges.data();
  3312. edges2Count = m_potentialEdges.size();
  3313. }
  3314. uint32_t prevEdge = UINT32_MAX; // Handle potential edges duplicates.
  3315. for (; j < edges2Count; j++) {
  3316. const uint32_t edge2 = edges2[j];
  3317. if (edge1 == edge2)
  3318. continue;
  3319. if (edge2 == prevEdge)
  3320. continue;
  3321. prevEdge = edge2;
  3322. // Check if edge2 is ignored.
  3323. bool ignore = false;
  3324. for (uint32_t k = 0; k < ignoreEdges.length; k++) {
  3325. if (edge2 == ignoreEdges[k]) {
  3326. ignore = true;
  3327. break;
  3328. }
  3329. }
  3330. if (ignore)
  3331. continue;
  3332. const uint32_t edge2Vertex[2] = { vertexAt(meshEdgeIndex0(edge2)), vertexAt(meshEdgeIndex1(edge2)) };
  3333. // Ignore connected edges, since they can't intersect (only overlap), and may be detected as false positives.
  3334. if (edge1Vertex[0] == edge2Vertex[0] || edge1Vertex[0] == edge2Vertex[1] || edge1Vertex[1] == edge2Vertex[0] || edge1Vertex[1] == edge2Vertex[1])
  3335. continue;
  3336. const Vector2 &edge2Position1 = m_positions[edge2Vertex[0]];
  3337. const Vector2 &edge2Position2 = m_positions[edge2Vertex[1]];
  3338. if (!Extents2::intersect(edge1Extents, Extents2(edge2Position1, edge2Position2)))
  3339. continue;
  3340. if (linesIntersect(edge1Position1, edge1Position2, edge2Position1, edge2Position2, epsilon))
  3341. return true;
  3342. }
  3343. }
  3344. return false;
  3345. }
  3346. #if XA_DEBUG_EXPORT_BOUNDARY_GRID
  3347. void debugExport(const char *filename)
  3348. {
  3349. Array<uint8_t> image;
  3350. image.resize(m_gridWidth * m_gridHeight * 3);
  3351. for (uint32_t y = 0; y < m_gridHeight; y++) {
  3352. for (uint32_t x = 0; x < m_gridWidth; x++) {
  3353. uint8_t *bgr = &image[(x + y * m_gridWidth) * 3];
  3354. bgr[0] = bgr[1] = bgr[2] = 32;
  3355. uint32_t offset = m_cellDataOffsets[x + y * m_gridWidth];
  3356. while (offset != UINT32_MAX) {
  3357. const uint32_t edge2 = m_cellData[offset];
  3358. srand(edge2);
  3359. for (uint32_t i = 0; i < 3; i++)
  3360. bgr[i] = uint8_t(bgr[i] * 0.5f + (rand() % 255) * 0.5f);
  3361. offset = m_cellData[offset + 1];
  3362. }
  3363. }
  3364. }
  3365. WriteTga(filename, image.data(), m_gridWidth, m_gridHeight);
  3366. }
  3367. #endif
  3368. private:
  3369. bool createGrid()
  3370. {
  3371. // Compute edge extents. Min will be the grid origin.
  3372. const uint32_t edgeCount = m_edges.size();
  3373. Extents2 edgeExtents;
  3374. edgeExtents.reset();
  3375. for (uint32_t i = 0; i < edgeCount; i++) {
  3376. const uint32_t edge = m_edges[i];
  3377. edgeExtents.add(edgePosition0(edge));
  3378. edgeExtents.add(edgePosition1(edge));
  3379. }
  3380. m_gridOrigin = edgeExtents.min;
  3381. // Size grid to approximately one edge per cell in the largest dimension.
  3382. const Vector2 extentsSize(edgeExtents.max - edgeExtents.min);
  3383. m_cellSize = max(extentsSize.x, extentsSize.y) / (float)clamp(edgeCount, 32u, 512u);
  3384. if (m_cellSize <= 0.0f)
  3385. return false;
  3386. m_gridWidth = uint32_t(ceilf(extentsSize.x / m_cellSize));
  3387. m_gridHeight = uint32_t(ceilf(extentsSize.y / m_cellSize));
  3388. if (m_gridWidth <= 1 || m_gridHeight <= 1)
  3389. return false;
  3390. // Insert edges into cells.
  3391. m_cellDataOffsets.resize(m_gridWidth * m_gridHeight);
  3392. for (uint32_t i = 0; i < m_cellDataOffsets.size(); i++)
  3393. m_cellDataOffsets[i] = UINT32_MAX;
  3394. m_cellData.clear();
  3395. m_cellData.reserve(edgeCount * 2);
  3396. for (uint32_t i = 0; i < edgeCount; i++) {
  3397. const uint32_t edge = m_edges[i];
  3398. traverse(edgePosition0(edge), edgePosition1(edge));
  3399. XA_DEBUG_ASSERT(!m_traversedCellOffsets.isEmpty());
  3400. for (uint32_t j = 0; j < m_traversedCellOffsets.size(); j++) {
  3401. const uint32_t cell = m_traversedCellOffsets[j];
  3402. uint32_t offset = m_cellDataOffsets[cell];
  3403. if (offset == UINT32_MAX)
  3404. m_cellDataOffsets[cell] = m_cellData.size();
  3405. else {
  3406. for (;;) {
  3407. uint32_t &nextOffset = m_cellData[offset + 1];
  3408. if (nextOffset == UINT32_MAX) {
  3409. nextOffset = m_cellData.size();
  3410. break;
  3411. }
  3412. offset = nextOffset;
  3413. }
  3414. }
  3415. m_cellData.push_back(edge);
  3416. m_cellData.push_back(UINT32_MAX);
  3417. }
  3418. }
  3419. return true;
  3420. }
  3421. void computePotentialEdges(Vector2 p1, Vector2 p2)
  3422. {
  3423. m_potentialEdges.clear();
  3424. traverse(p1, p2);
  3425. for (uint32_t j = 0; j < m_traversedCellOffsets.size(); j++) {
  3426. const uint32_t cell = m_traversedCellOffsets[j];
  3427. uint32_t offset = m_cellDataOffsets[cell];
  3428. while (offset != UINT32_MAX) {
  3429. const uint32_t edge2 = m_cellData[offset];
  3430. m_potentialEdges.push_back(edge2);
  3431. offset = m_cellData[offset + 1];
  3432. }
  3433. }
  3434. if (m_potentialEdges.isEmpty())
  3435. return;
  3436. insertionSort(m_potentialEdges.data(), m_potentialEdges.size());
  3437. }
  3438. // "A Fast Voxel Traversal Algorithm for Ray Tracing"
  3439. void traverse(Vector2 p1, Vector2 p2)
  3440. {
  3441. const Vector2 dir = p2 - p1;
  3442. const Vector2 normal = normalizeSafe(dir, Vector2(0.0f));
  3443. const int stepX = dir.x >= 0 ? 1 : -1;
  3444. const int stepY = dir.y >= 0 ? 1 : -1;
  3445. const uint32_t firstCell[2] = { cellX(p1.x), cellY(p1.y) };
  3446. const uint32_t lastCell[2] = { cellX(p2.x), cellY(p2.y) };
  3447. float distToNextCellX;
  3448. if (stepX == 1)
  3449. distToNextCellX = (firstCell[0] + 1) * m_cellSize - (p1.x - m_gridOrigin.x);
  3450. else
  3451. distToNextCellX = (p1.x - m_gridOrigin.x) - firstCell[0] * m_cellSize;
  3452. float distToNextCellY;
  3453. if (stepY == 1)
  3454. distToNextCellY = (firstCell[1] + 1) * m_cellSize - (p1.y - m_gridOrigin.y);
  3455. else
  3456. distToNextCellY = (p1.y - m_gridOrigin.y) - firstCell[1] * m_cellSize;
  3457. float tMaxX, tMaxY, tDeltaX, tDeltaY;
  3458. if (normal.x > kEpsilon || normal.x < -kEpsilon) {
  3459. tMaxX = (distToNextCellX * stepX) / normal.x;
  3460. tDeltaX = (m_cellSize * stepX) / normal.x;
  3461. }
  3462. else
  3463. tMaxX = tDeltaX = FLT_MAX;
  3464. if (normal.y > kEpsilon || normal.y < -kEpsilon) {
  3465. tMaxY = (distToNextCellY * stepY) / normal.y;
  3466. tDeltaY = (m_cellSize * stepY) / normal.y;
  3467. }
  3468. else
  3469. tMaxY = tDeltaY = FLT_MAX;
  3470. m_traversedCellOffsets.clear();
  3471. m_traversedCellOffsets.push_back(firstCell[0] + firstCell[1] * m_gridWidth);
  3472. uint32_t currentCell[2] = { firstCell[0], firstCell[1] };
  3473. while (!(currentCell[0] == lastCell[0] && currentCell[1] == lastCell[1])) {
  3474. if (tMaxX < tMaxY) {
  3475. tMaxX += tDeltaX;
  3476. currentCell[0] += stepX;
  3477. } else {
  3478. tMaxY += tDeltaY;
  3479. currentCell[1] += stepY;
  3480. }
  3481. if (currentCell[0] >= m_gridWidth || currentCell[1] >= m_gridHeight)
  3482. break;
  3483. if (stepX == -1 && currentCell[0] < lastCell[0])
  3484. break;
  3485. if (stepX == 1 && currentCell[0] > lastCell[0])
  3486. break;
  3487. if (stepY == -1 && currentCell[1] < lastCell[1])
  3488. break;
  3489. if (stepY == 1 && currentCell[1] > lastCell[1])
  3490. break;
  3491. m_traversedCellOffsets.push_back(currentCell[0] + currentCell[1] * m_gridWidth);
  3492. }
  3493. }
  3494. uint32_t cellX(float x) const
  3495. {
  3496. return min((uint32_t)max(0.0f, (x - m_gridOrigin.x) / m_cellSize), m_gridWidth - 1u);
  3497. }
  3498. uint32_t cellY(float y) const
  3499. {
  3500. return min((uint32_t)max(0.0f, (y - m_gridOrigin.y) / m_cellSize), m_gridHeight - 1u);
  3501. }
  3502. Vector2 edgePosition0(uint32_t edge) const
  3503. {
  3504. return m_positions[vertexAt(meshEdgeIndex0(edge))];
  3505. }
  3506. Vector2 edgePosition1(uint32_t edge) const
  3507. {
  3508. return m_positions[vertexAt(meshEdgeIndex1(edge))];
  3509. }
  3510. uint32_t vertexAt(uint32_t index) const
  3511. {
  3512. return m_indices.length > 0 ? m_indices[index] : index;
  3513. }
  3514. Array<uint32_t> m_edges;
  3515. ConstArrayView<Vector2> m_positions;
  3516. ConstArrayView<uint32_t> m_indices; // Optional. Empty if unused.
  3517. float m_cellSize;
  3518. Vector2 m_gridOrigin;
  3519. uint32_t m_gridWidth, m_gridHeight; // in cells
  3520. Array<uint32_t> m_cellDataOffsets;
  3521. Array<uint32_t> m_cellData;
  3522. Array<uint32_t> m_potentialEdges;
  3523. Array<uint32_t> m_traversedCellOffsets;
  3524. };
  3525. struct UvMeshChart
  3526. {
  3527. Array<uint32_t> faces;
  3528. Array<uint32_t> indices;
  3529. uint32_t material;
  3530. };
  3531. struct UvMesh
  3532. {
  3533. UvMeshDecl decl;
  3534. BitArray faceIgnore;
  3535. Array<uint32_t> faceMaterials;
  3536. Array<uint32_t> indices;
  3537. Array<Vector2> texcoords; // Copied from input and never modified, UvMeshInstance::texcoords are. Used to restore UvMeshInstance::texcoords so packing can be run multiple times.
  3538. Array<UvMeshChart *> charts;
  3539. Array<uint32_t> vertexToChartMap;
  3540. };
  3541. struct UvMeshInstance
  3542. {
  3543. UvMesh *mesh;
  3544. Array<Vector2> texcoords;
  3545. };
  3546. /*
  3547. * Copyright (c) 2004-2010, Bruno Levy
  3548. * All rights reserved.
  3549. *
  3550. * Redistribution and use in source and binary forms, with or without
  3551. * modification, are permitted provided that the following conditions are met:
  3552. *
  3553. * * Redistributions of source code must retain the above copyright notice,
  3554. * this list of conditions and the following disclaimer.
  3555. * * Redistributions in binary form must reproduce the above copyright notice,
  3556. * this list of conditions and the following disclaimer in the documentation
  3557. * and/or other materials provided with the distribution.
  3558. * * Neither the name of the ALICE Project-Team nor the names of its
  3559. * contributors may be used to endorse or promote products derived from this
  3560. * software without specific prior written permission.
  3561. *
  3562. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3563. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3564. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3565. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  3566. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  3567. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  3568. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  3569. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  3570. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  3571. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  3572. * POSSIBILITY OF SUCH DAMAGE.
  3573. *
  3574. * If you modify this software, you should include a notice giving the
  3575. * name of the person performing the modification, the date of modification,
  3576. * and the reason for such modification.
  3577. *
  3578. * Contact: Bruno Levy
  3579. *
  3580. * levy@loria.fr
  3581. *
  3582. * ALICE Project
  3583. * LORIA, INRIA Lorraine,
  3584. * Campus Scientifique, BP 239
  3585. * 54506 VANDOEUVRE LES NANCY CEDEX
  3586. * FRANCE
  3587. */
  3588. namespace opennl {
  3589. #define NL_NEW(T) XA_ALLOC(MemTag::OpenNL, T)
  3590. #define NL_NEW_ARRAY(T,NB) XA_ALLOC_ARRAY(MemTag::OpenNL, T, NB)
  3591. #define NL_RENEW_ARRAY(T,x,NB) XA_REALLOC(MemTag::OpenNL, x, T, NB)
  3592. #define NL_DELETE(x) XA_FREE(x); x = nullptr
  3593. #define NL_DELETE_ARRAY(x) XA_FREE(x); x = nullptr
  3594. #define NL_CLEAR(x, T) memset(x, 0, sizeof(T));
  3595. #define NL_CLEAR_ARRAY(T,x,NB) memset(x, 0, (size_t)(NB)*sizeof(T))
  3596. #define NL_NEW_VECTOR(dim) XA_ALLOC_ARRAY(MemTag::OpenNL, double, dim)
  3597. #define NL_DELETE_VECTOR(ptr) XA_FREE(ptr)
  3598. struct NLMatrixStruct;
  3599. typedef NLMatrixStruct * NLMatrix;
  3600. typedef void (*NLDestroyMatrixFunc)(NLMatrix M);
  3601. typedef void (*NLMultMatrixVectorFunc)(NLMatrix M, const double* x, double* y);
  3602. #define NL_MATRIX_SPARSE_DYNAMIC 0x1001
  3603. #define NL_MATRIX_CRS 0x1002
  3604. #define NL_MATRIX_OTHER 0x1006
  3605. struct NLMatrixStruct
  3606. {
  3607. uint32_t m;
  3608. uint32_t n;
  3609. uint32_t type;
  3610. NLDestroyMatrixFunc destroy_func;
  3611. NLMultMatrixVectorFunc mult_func;
  3612. };
  3613. /* Dynamic arrays for sparse row/columns */
  3614. struct NLCoeff
  3615. {
  3616. uint32_t index;
  3617. double value;
  3618. };
  3619. struct NLRowColumn
  3620. {
  3621. uint32_t size;
  3622. uint32_t capacity;
  3623. NLCoeff* coeff;
  3624. };
  3625. /* Compressed Row Storage */
  3626. struct NLCRSMatrix
  3627. {
  3628. uint32_t m;
  3629. uint32_t n;
  3630. uint32_t type;
  3631. NLDestroyMatrixFunc destroy_func;
  3632. NLMultMatrixVectorFunc mult_func;
  3633. double* val;
  3634. uint32_t* rowptr;
  3635. uint32_t* colind;
  3636. uint32_t nslices;
  3637. uint32_t* sliceptr;
  3638. };
  3639. /* SparseMatrix data structure */
  3640. struct NLSparseMatrix
  3641. {
  3642. uint32_t m;
  3643. uint32_t n;
  3644. uint32_t type;
  3645. NLDestroyMatrixFunc destroy_func;
  3646. NLMultMatrixVectorFunc mult_func;
  3647. uint32_t diag_size;
  3648. uint32_t diag_capacity;
  3649. NLRowColumn* row;
  3650. NLRowColumn* column;
  3651. double* diag;
  3652. uint32_t row_capacity;
  3653. uint32_t column_capacity;
  3654. };
  3655. /* NLContext data structure */
  3656. struct NLBufferBinding
  3657. {
  3658. void* base_address;
  3659. uint32_t stride;
  3660. };
  3661. #define NL_BUFFER_ITEM(B,i) *(double*)((void*)((char*)((B).base_address)+((i)*(B).stride)))
  3662. struct NLContext
  3663. {
  3664. NLBufferBinding *variable_buffer;
  3665. double *variable_value;
  3666. bool *variable_is_locked;
  3667. uint32_t *variable_index;
  3668. uint32_t n;
  3669. NLMatrix M;
  3670. NLMatrix P;
  3671. NLMatrix B;
  3672. NLRowColumn af;
  3673. NLRowColumn al;
  3674. double *x;
  3675. double *b;
  3676. uint32_t nb_variables;
  3677. uint32_t nb_systems;
  3678. uint32_t current_row;
  3679. uint32_t max_iterations;
  3680. bool max_iterations_defined;
  3681. double threshold;
  3682. double omega;
  3683. uint32_t used_iterations;
  3684. double error;
  3685. };
  3686. static void nlDeleteMatrix(NLMatrix M)
  3687. {
  3688. if (!M)
  3689. return;
  3690. M->destroy_func(M);
  3691. NL_DELETE(M);
  3692. }
  3693. static void nlMultMatrixVector(NLMatrix M, const double* x, double* y)
  3694. {
  3695. M->mult_func(M, x, y);
  3696. }
  3697. static void nlRowColumnConstruct(NLRowColumn* c)
  3698. {
  3699. c->size = 0;
  3700. c->capacity = 0;
  3701. c->coeff = nullptr;
  3702. }
  3703. static void nlRowColumnDestroy(NLRowColumn* c)
  3704. {
  3705. NL_DELETE_ARRAY(c->coeff);
  3706. c->size = 0;
  3707. c->capacity = 0;
  3708. }
  3709. static void nlRowColumnGrow(NLRowColumn* c)
  3710. {
  3711. if (c->capacity != 0) {
  3712. c->capacity = 2 * c->capacity;
  3713. c->coeff = NL_RENEW_ARRAY(NLCoeff, c->coeff, c->capacity);
  3714. } else {
  3715. c->capacity = 4;
  3716. c->coeff = NL_NEW_ARRAY(NLCoeff, c->capacity);
  3717. NL_CLEAR_ARRAY(NLCoeff, c->coeff, c->capacity);
  3718. }
  3719. }
  3720. static void nlRowColumnAdd(NLRowColumn* c, uint32_t index, double value)
  3721. {
  3722. for (uint32_t i = 0; i < c->size; i++) {
  3723. if (c->coeff[i].index == index) {
  3724. c->coeff[i].value += value;
  3725. return;
  3726. }
  3727. }
  3728. if (c->size == c->capacity)
  3729. nlRowColumnGrow(c);
  3730. c->coeff[c->size].index = index;
  3731. c->coeff[c->size].value = value;
  3732. c->size++;
  3733. }
  3734. /* Does not check whether the index already exists */
  3735. static void nlRowColumnAppend(NLRowColumn* c, uint32_t index, double value)
  3736. {
  3737. if (c->size == c->capacity)
  3738. nlRowColumnGrow(c);
  3739. c->coeff[c->size].index = index;
  3740. c->coeff[c->size].value = value;
  3741. c->size++;
  3742. }
  3743. static void nlRowColumnZero(NLRowColumn* c)
  3744. {
  3745. c->size = 0;
  3746. }
  3747. static void nlRowColumnClear(NLRowColumn* c)
  3748. {
  3749. c->size = 0;
  3750. c->capacity = 0;
  3751. NL_DELETE_ARRAY(c->coeff);
  3752. }
  3753. static int nlCoeffCompare(const void* p1, const void* p2)
  3754. {
  3755. return (((NLCoeff*)(p2))->index < ((NLCoeff*)(p1))->index);
  3756. }
  3757. static void nlRowColumnSort(NLRowColumn* c)
  3758. {
  3759. qsort(c->coeff, c->size, sizeof(NLCoeff), nlCoeffCompare);
  3760. }
  3761. /* CRSMatrix data structure */
  3762. static void nlCRSMatrixDestroy(NLCRSMatrix* M)
  3763. {
  3764. NL_DELETE_ARRAY(M->val);
  3765. NL_DELETE_ARRAY(M->rowptr);
  3766. NL_DELETE_ARRAY(M->colind);
  3767. NL_DELETE_ARRAY(M->sliceptr);
  3768. M->m = 0;
  3769. M->n = 0;
  3770. M->nslices = 0;
  3771. }
  3772. static void nlCRSMatrixMultSlice(NLCRSMatrix* M, const double* x, double* y, uint32_t Ibegin, uint32_t Iend)
  3773. {
  3774. for (uint32_t i = Ibegin; i < Iend; ++i) {
  3775. double sum = 0.0;
  3776. for (uint32_t j = M->rowptr[i]; j < M->rowptr[i + 1]; ++j)
  3777. sum += M->val[j] * x[M->colind[j]];
  3778. y[i] = sum;
  3779. }
  3780. }
  3781. static void nlCRSMatrixMult(NLCRSMatrix* M, const double* x, double* y)
  3782. {
  3783. int nslices = (int)(M->nslices);
  3784. for (int slice = 0; slice < nslices; ++slice)
  3785. nlCRSMatrixMultSlice(M, x, y, M->sliceptr[slice], M->sliceptr[slice + 1]);
  3786. }
  3787. static void nlCRSMatrixConstruct(NLCRSMatrix* M, uint32_t m, uint32_t n, uint32_t nnz, uint32_t nslices)
  3788. {
  3789. M->m = m;
  3790. M->n = n;
  3791. M->type = NL_MATRIX_CRS;
  3792. M->destroy_func = (NLDestroyMatrixFunc)nlCRSMatrixDestroy;
  3793. M->mult_func = (NLMultMatrixVectorFunc)nlCRSMatrixMult;
  3794. M->nslices = nslices;
  3795. M->val = NL_NEW_ARRAY(double, nnz);
  3796. NL_CLEAR_ARRAY(double, M->val, nnz);
  3797. M->rowptr = NL_NEW_ARRAY(uint32_t, m + 1);
  3798. NL_CLEAR_ARRAY(uint32_t, M->rowptr, m + 1);
  3799. M->colind = NL_NEW_ARRAY(uint32_t, nnz);
  3800. NL_CLEAR_ARRAY(uint32_t, M->colind, nnz);
  3801. M->sliceptr = NL_NEW_ARRAY(uint32_t, nslices + 1);
  3802. NL_CLEAR_ARRAY(uint32_t, M->sliceptr, nslices + 1);
  3803. }
  3804. /* SparseMatrix data structure */
  3805. static void nlSparseMatrixDestroyRowColumns(NLSparseMatrix* M)
  3806. {
  3807. for (uint32_t i = 0; i < M->m; i++)
  3808. nlRowColumnDestroy(&(M->row[i]));
  3809. NL_DELETE_ARRAY(M->row);
  3810. }
  3811. static void nlSparseMatrixDestroy(NLSparseMatrix* M)
  3812. {
  3813. XA_DEBUG_ASSERT(M->type == NL_MATRIX_SPARSE_DYNAMIC);
  3814. nlSparseMatrixDestroyRowColumns(M);
  3815. NL_DELETE_ARRAY(M->diag);
  3816. }
  3817. static void nlSparseMatrixAdd(NLSparseMatrix* M, uint32_t i, uint32_t j, double value)
  3818. {
  3819. XA_DEBUG_ASSERT(i >= 0 && i <= M->m - 1);
  3820. XA_DEBUG_ASSERT(j >= 0 && j <= M->n - 1);
  3821. if (i == j)
  3822. M->diag[i] += value;
  3823. nlRowColumnAdd(&(M->row[i]), j, value);
  3824. }
  3825. /* Returns the number of non-zero coefficients */
  3826. static uint32_t nlSparseMatrixNNZ(NLSparseMatrix* M)
  3827. {
  3828. uint32_t nnz = 0;
  3829. for (uint32_t i = 0; i < M->m; i++)
  3830. nnz += M->row[i].size;
  3831. return nnz;
  3832. }
  3833. static void nlSparseMatrixSort(NLSparseMatrix* M)
  3834. {
  3835. for (uint32_t i = 0; i < M->m; i++)
  3836. nlRowColumnSort(&(M->row[i]));
  3837. }
  3838. /* SparseMatrix x Vector routines, internal helper routines */
  3839. static void nlSparseMatrix_mult_rows(NLSparseMatrix* A, const double* x, double* y)
  3840. {
  3841. /*
  3842. * Note: OpenMP does not like unsigned ints
  3843. * (causes some floating point exceptions),
  3844. * therefore I use here signed ints for all
  3845. * indices.
  3846. */
  3847. int m = (int)(A->m);
  3848. NLCoeff* c = nullptr;
  3849. NLRowColumn* Ri = nullptr;
  3850. for (int i = 0; i < m; i++) {
  3851. Ri = &(A->row[i]);
  3852. y[i] = 0;
  3853. for (int ij = 0; ij < (int)(Ri->size); ij++) {
  3854. c = &(Ri->coeff[ij]);
  3855. y[i] += c->value * x[c->index];
  3856. }
  3857. }
  3858. }
  3859. static void nlSparseMatrixMult(NLSparseMatrix* A, const double* x, double* y)
  3860. {
  3861. XA_DEBUG_ASSERT(A->type == NL_MATRIX_SPARSE_DYNAMIC);
  3862. nlSparseMatrix_mult_rows(A, x, y);
  3863. }
  3864. static void nlSparseMatrixConstruct(NLSparseMatrix* M, uint32_t m, uint32_t n)
  3865. {
  3866. M->m = m;
  3867. M->n = n;
  3868. M->type = NL_MATRIX_SPARSE_DYNAMIC;
  3869. M->destroy_func = (NLDestroyMatrixFunc)nlSparseMatrixDestroy;
  3870. M->mult_func = (NLMultMatrixVectorFunc)nlSparseMatrixMult;
  3871. M->row = NL_NEW_ARRAY(NLRowColumn, m);
  3872. NL_CLEAR_ARRAY(NLRowColumn, M->row, m);
  3873. M->row_capacity = m;
  3874. for (uint32_t i = 0; i < n; i++)
  3875. nlRowColumnConstruct(&(M->row[i]));
  3876. M->row_capacity = 0;
  3877. M->column = nullptr;
  3878. M->column_capacity = 0;
  3879. M->diag_size = min(m, n);
  3880. M->diag_capacity = M->diag_size;
  3881. M->diag = NL_NEW_ARRAY(double, M->diag_size);
  3882. NL_CLEAR_ARRAY(double, M->diag, M->diag_size);
  3883. }
  3884. static NLMatrix nlCRSMatrixNewFromSparseMatrix(NLSparseMatrix* M)
  3885. {
  3886. uint32_t nnz = nlSparseMatrixNNZ(M);
  3887. uint32_t nslices = 8; /* TODO: get number of cores */
  3888. uint32_t slice, cur_bound, cur_NNZ, cur_row;
  3889. uint32_t k;
  3890. uint32_t slice_size = nnz / nslices;
  3891. NLCRSMatrix* CRS = NL_NEW(NLCRSMatrix);
  3892. NL_CLEAR(CRS, NLCRSMatrix);
  3893. nlCRSMatrixConstruct(CRS, M->m, M->n, nnz, nslices);
  3894. nlSparseMatrixSort(M);
  3895. /* Convert matrix to CRS format */
  3896. k = 0;
  3897. for (uint32_t i = 0; i < M->m; ++i) {
  3898. NLRowColumn* Ri = &(M->row[i]);
  3899. CRS->rowptr[i] = k;
  3900. for (uint32_t ij = 0; ij < Ri->size; ij++) {
  3901. NLCoeff* c = &(Ri->coeff[ij]);
  3902. CRS->val[k] = c->value;
  3903. CRS->colind[k] = c->index;
  3904. ++k;
  3905. }
  3906. }
  3907. CRS->rowptr[M->m] = k;
  3908. /* Create "slices" to be used by parallel sparse matrix vector product */
  3909. if (CRS->sliceptr) {
  3910. cur_bound = slice_size;
  3911. cur_NNZ = 0;
  3912. cur_row = 0;
  3913. CRS->sliceptr[0] = 0;
  3914. for (slice = 1; slice < nslices; ++slice) {
  3915. while (cur_NNZ < cur_bound && cur_row < M->m) {
  3916. cur_NNZ += CRS->rowptr[cur_row + 1] - CRS->rowptr[cur_row];
  3917. ++cur_row;
  3918. }
  3919. CRS->sliceptr[slice] = cur_row;
  3920. cur_bound += slice_size;
  3921. }
  3922. CRS->sliceptr[nslices] = M->m;
  3923. }
  3924. return (NLMatrix)CRS;
  3925. }
  3926. static void nlMatrixCompress(NLMatrix* M)
  3927. {
  3928. NLMatrix CRS = nullptr;
  3929. if ((*M)->type != NL_MATRIX_SPARSE_DYNAMIC)
  3930. return;
  3931. CRS = nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)*M);
  3932. nlDeleteMatrix(*M);
  3933. *M = CRS;
  3934. }
  3935. static NLContext *nlNewContext()
  3936. {
  3937. NLContext* result = NL_NEW(NLContext);
  3938. NL_CLEAR(result, NLContext);
  3939. result->max_iterations = 100;
  3940. result->threshold = 1e-6;
  3941. result->omega = 1.5;
  3942. result->nb_systems = 1;
  3943. return result;
  3944. }
  3945. static void nlDeleteContext(NLContext *context)
  3946. {
  3947. nlDeleteMatrix(context->M);
  3948. context->M = nullptr;
  3949. nlDeleteMatrix(context->P);
  3950. context->P = nullptr;
  3951. nlDeleteMatrix(context->B);
  3952. context->B = nullptr;
  3953. nlRowColumnDestroy(&context->af);
  3954. nlRowColumnDestroy(&context->al);
  3955. NL_DELETE_ARRAY(context->variable_value);
  3956. NL_DELETE_ARRAY(context->variable_buffer);
  3957. NL_DELETE_ARRAY(context->variable_is_locked);
  3958. NL_DELETE_ARRAY(context->variable_index);
  3959. NL_DELETE_ARRAY(context->x);
  3960. NL_DELETE_ARRAY(context->b);
  3961. NL_DELETE(context);
  3962. }
  3963. static double ddot(int n, const double *x, const double *y)
  3964. {
  3965. double sum = 0.0;
  3966. for (int i = 0; i < n; i++)
  3967. sum += x[i] * y[i];
  3968. return sum;
  3969. }
  3970. static void daxpy(int n, double a, const double *x, double *y)
  3971. {
  3972. for (int i = 0; i < n; i++)
  3973. y[i] = a * x[i] + y[i];
  3974. }
  3975. static void dscal(int n, double a, double *x)
  3976. {
  3977. for (int i = 0; i < n; i++)
  3978. x[i] *= a;
  3979. }
  3980. /*
  3981. * The implementation of the solvers is inspired by
  3982. * the lsolver library, by Christian Badura, available from:
  3983. * http://www.mathematik.uni-freiburg.de
  3984. * /IAM/Research/projectskr/lin_solver/
  3985. *
  3986. * About the Conjugate Gradient, details can be found in:
  3987. * Ashby, Manteuffel, Saylor
  3988. * A taxononmy for conjugate gradient methods
  3989. * SIAM J Numer Anal 27, 1542-1568 (1990)
  3990. *
  3991. * This version is completely abstract, the same code can be used for
  3992. * CPU/GPU, dense matrix / sparse matrix etc...
  3993. * Abstraction is realized through:
  3994. * - Abstract matrix interface (NLMatrix), that can implement different
  3995. * versions of matrix x vector product (CPU/GPU, sparse/dense ...)
  3996. */
  3997. static uint32_t nlSolveSystem_PRE_CG(NLMatrix M, NLMatrix P, double* b, double* x, double eps, uint32_t max_iter, double *sq_bnorm, double *sq_rnorm)
  3998. {
  3999. int N = (int)M->n;
  4000. double* r = NL_NEW_VECTOR(N);
  4001. double* d = NL_NEW_VECTOR(N);
  4002. double* h = NL_NEW_VECTOR(N);
  4003. double *Ad = h;
  4004. uint32_t its = 0;
  4005. double rh, alpha, beta;
  4006. double b_square = ddot(N, b, b);
  4007. double err = eps * eps*b_square;
  4008. double curr_err;
  4009. nlMultMatrixVector(M, x, r);
  4010. daxpy(N, -1., b, r);
  4011. nlMultMatrixVector(P, r, d);
  4012. memcpy(h, d, N * sizeof(double));
  4013. rh = ddot(N, r, h);
  4014. curr_err = ddot(N, r, r);
  4015. while (curr_err > err && its < max_iter) {
  4016. nlMultMatrixVector(M, d, Ad);
  4017. alpha = rh / ddot(N, d, Ad);
  4018. daxpy(N, -alpha, d, x);
  4019. daxpy(N, -alpha, Ad, r);
  4020. nlMultMatrixVector(P, r, h);
  4021. beta = 1. / rh;
  4022. rh = ddot(N, r, h);
  4023. beta *= rh;
  4024. dscal(N, beta, d);
  4025. daxpy(N, 1., h, d);
  4026. ++its;
  4027. curr_err = ddot(N, r, r);
  4028. }
  4029. NL_DELETE_VECTOR(r);
  4030. NL_DELETE_VECTOR(d);
  4031. NL_DELETE_VECTOR(h);
  4032. *sq_bnorm = b_square;
  4033. *sq_rnorm = curr_err;
  4034. return its;
  4035. }
  4036. static uint32_t nlSolveSystemIterative(NLContext *context, NLMatrix M, NLMatrix P, double* b_in, double* x_in, double eps, uint32_t max_iter)
  4037. {
  4038. uint32_t result = 0;
  4039. double rnorm = 0.0;
  4040. double bnorm = 0.0;
  4041. double* b = b_in;
  4042. double* x = x_in;
  4043. XA_DEBUG_ASSERT(M->m == M->n);
  4044. double sq_bnorm, sq_rnorm;
  4045. result = nlSolveSystem_PRE_CG(M, P, b, x, eps, max_iter, &sq_bnorm, &sq_rnorm);
  4046. /* Get residual norm and rhs norm */
  4047. bnorm = sqrt(sq_bnorm);
  4048. rnorm = sqrt(sq_rnorm);
  4049. if (bnorm == 0.0)
  4050. context->error = rnorm;
  4051. else
  4052. context->error = rnorm / bnorm;
  4053. context->used_iterations = result;
  4054. return result;
  4055. }
  4056. static bool nlSolveIterative(NLContext *context)
  4057. {
  4058. double* b = context->b;
  4059. double* x = context->x;
  4060. uint32_t n = context->n;
  4061. NLMatrix M = context->M;
  4062. NLMatrix P = context->P;
  4063. for (uint32_t k = 0; k < context->nb_systems; ++k) {
  4064. nlSolveSystemIterative(context, M, P, b, x, context->threshold, context->max_iterations);
  4065. b += n;
  4066. x += n;
  4067. }
  4068. return true;
  4069. }
  4070. struct NLJacobiPreconditioner
  4071. {
  4072. uint32_t m;
  4073. uint32_t n;
  4074. uint32_t type;
  4075. NLDestroyMatrixFunc destroy_func;
  4076. NLMultMatrixVectorFunc mult_func;
  4077. double* diag_inv;
  4078. };
  4079. static void nlJacobiPreconditionerDestroy(NLJacobiPreconditioner* M)
  4080. {
  4081. NL_DELETE_ARRAY(M->diag_inv);
  4082. }
  4083. static void nlJacobiPreconditionerMult(NLJacobiPreconditioner* M, const double* x, double* y)
  4084. {
  4085. for (uint32_t i = 0; i < M->n; ++i)
  4086. y[i] = x[i] * M->diag_inv[i];
  4087. }
  4088. static NLMatrix nlNewJacobiPreconditioner(NLMatrix M_in)
  4089. {
  4090. NLSparseMatrix* M = nullptr;
  4091. NLJacobiPreconditioner* result = nullptr;
  4092. XA_DEBUG_ASSERT(M_in->type == NL_MATRIX_SPARSE_DYNAMIC);
  4093. XA_DEBUG_ASSERT(M_in->m == M_in->n);
  4094. M = (NLSparseMatrix*)M_in;
  4095. result = NL_NEW(NLJacobiPreconditioner);
  4096. NL_CLEAR(result, NLJacobiPreconditioner);
  4097. result->m = M->m;
  4098. result->n = M->n;
  4099. result->type = NL_MATRIX_OTHER;
  4100. result->destroy_func = (NLDestroyMatrixFunc)nlJacobiPreconditionerDestroy;
  4101. result->mult_func = (NLMultMatrixVectorFunc)nlJacobiPreconditionerMult;
  4102. result->diag_inv = NL_NEW_ARRAY(double, M->n);
  4103. NL_CLEAR_ARRAY(double, result->diag_inv, M->n);
  4104. for (uint32_t i = 0; i < M->n; ++i)
  4105. result->diag_inv[i] = (M->diag[i] == 0.0) ? 1.0 : 1.0 / M->diag[i];
  4106. return (NLMatrix)result;
  4107. }
  4108. #define NL_NB_VARIABLES 0x101
  4109. #define NL_MAX_ITERATIONS 0x103
  4110. static void nlSolverParameteri(NLContext *context, uint32_t pname, int param)
  4111. {
  4112. if (pname == NL_NB_VARIABLES) {
  4113. XA_DEBUG_ASSERT(param > 0);
  4114. context->nb_variables = (uint32_t)param;
  4115. } else if (pname == NL_MAX_ITERATIONS) {
  4116. XA_DEBUG_ASSERT(param > 0);
  4117. context->max_iterations = (uint32_t)param;
  4118. context->max_iterations_defined = true;
  4119. }
  4120. }
  4121. static void nlSetVariable(NLContext *context, uint32_t index, double value)
  4122. {
  4123. XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
  4124. NL_BUFFER_ITEM(context->variable_buffer[0], index) = value;
  4125. }
  4126. static double nlGetVariable(NLContext *context, uint32_t index)
  4127. {
  4128. XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
  4129. return NL_BUFFER_ITEM(context->variable_buffer[0], index);
  4130. }
  4131. static void nlLockVariable(NLContext *context, uint32_t index)
  4132. {
  4133. XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
  4134. context->variable_is_locked[index] = true;
  4135. }
  4136. static void nlVariablesToVector(NLContext *context)
  4137. {
  4138. uint32_t n = context->n;
  4139. XA_DEBUG_ASSERT(context->x);
  4140. for (uint32_t k = 0; k < context->nb_systems; ++k) {
  4141. for (uint32_t i = 0; i < context->nb_variables; ++i) {
  4142. if (!context->variable_is_locked[i]) {
  4143. uint32_t index = context->variable_index[i];
  4144. XA_DEBUG_ASSERT(index < context->n);
  4145. double value = NL_BUFFER_ITEM(context->variable_buffer[k], i);
  4146. context->x[index + k * n] = value;
  4147. }
  4148. }
  4149. }
  4150. }
  4151. static void nlVectorToVariables(NLContext *context)
  4152. {
  4153. uint32_t n = context->n;
  4154. XA_DEBUG_ASSERT(context->x);
  4155. for (uint32_t k = 0; k < context->nb_systems; ++k) {
  4156. for (uint32_t i = 0; i < context->nb_variables; ++i) {
  4157. if (!context->variable_is_locked[i]) {
  4158. uint32_t index = context->variable_index[i];
  4159. XA_DEBUG_ASSERT(index < context->n);
  4160. double value = context->x[index + k * n];
  4161. NL_BUFFER_ITEM(context->variable_buffer[k], i) = value;
  4162. }
  4163. }
  4164. }
  4165. }
  4166. static void nlCoefficient(NLContext *context, uint32_t index, double value)
  4167. {
  4168. XA_DEBUG_ASSERT(index >= 0 && index <= context->nb_variables - 1);
  4169. if (context->variable_is_locked[index]) {
  4170. /*
  4171. * Note: in al, indices are NLvariable indices,
  4172. * within [0..nb_variables-1]
  4173. */
  4174. nlRowColumnAppend(&(context->al), index, value);
  4175. } else {
  4176. /*
  4177. * Note: in af, indices are system indices,
  4178. * within [0..n-1]
  4179. */
  4180. nlRowColumnAppend(&(context->af), context->variable_index[index], value);
  4181. }
  4182. }
  4183. #define NL_SYSTEM 0x0
  4184. #define NL_MATRIX 0x1
  4185. #define NL_ROW 0x2
  4186. static void nlBegin(NLContext *context, uint32_t prim)
  4187. {
  4188. if (prim == NL_SYSTEM) {
  4189. XA_DEBUG_ASSERT(context->nb_variables > 0);
  4190. context->variable_buffer = NL_NEW_ARRAY(NLBufferBinding, context->nb_systems);
  4191. NL_CLEAR_ARRAY(NLBufferBinding, context->variable_buffer, context->nb_systems);
  4192. context->variable_value = NL_NEW_ARRAY(double, context->nb_variables * context->nb_systems);
  4193. NL_CLEAR_ARRAY(double, context->variable_value, context->nb_variables * context->nb_systems);
  4194. for (uint32_t k = 0; k < context->nb_systems; ++k) {
  4195. context->variable_buffer[k].base_address =
  4196. context->variable_value +
  4197. k * context->nb_variables;
  4198. context->variable_buffer[k].stride = sizeof(double);
  4199. }
  4200. context->variable_is_locked = NL_NEW_ARRAY(bool, context->nb_variables);
  4201. NL_CLEAR_ARRAY(bool, context->variable_is_locked, context->nb_variables);
  4202. context->variable_index = NL_NEW_ARRAY(uint32_t, context->nb_variables);
  4203. NL_CLEAR_ARRAY(uint32_t, context->variable_index, context->nb_variables);
  4204. } else if (prim == NL_MATRIX) {
  4205. if (context->M)
  4206. return;
  4207. uint32_t n = 0;
  4208. for (uint32_t i = 0; i < context->nb_variables; i++) {
  4209. if (!context->variable_is_locked[i]) {
  4210. context->variable_index[i] = n;
  4211. n++;
  4212. } else
  4213. context->variable_index[i] = (uint32_t)~0;
  4214. }
  4215. context->n = n;
  4216. if (!context->max_iterations_defined)
  4217. context->max_iterations = n * 5;
  4218. context->M = (NLMatrix)(NL_NEW(NLSparseMatrix));
  4219. NL_CLEAR(context->M, NLSparseMatrix);
  4220. nlSparseMatrixConstruct((NLSparseMatrix*)(context->M), n, n);
  4221. context->x = NL_NEW_ARRAY(double, n*context->nb_systems);
  4222. NL_CLEAR_ARRAY(double, context->x, n*context->nb_systems);
  4223. context->b = NL_NEW_ARRAY(double, n*context->nb_systems);
  4224. NL_CLEAR_ARRAY(double, context->b, n*context->nb_systems);
  4225. nlVariablesToVector(context);
  4226. nlRowColumnConstruct(&context->af);
  4227. nlRowColumnConstruct(&context->al);
  4228. context->current_row = 0;
  4229. } else if (prim == NL_ROW) {
  4230. nlRowColumnZero(&context->af);
  4231. nlRowColumnZero(&context->al);
  4232. }
  4233. }
  4234. static void nlEnd(NLContext *context, uint32_t prim)
  4235. {
  4236. if (prim == NL_MATRIX) {
  4237. nlRowColumnClear(&context->af);
  4238. nlRowColumnClear(&context->al);
  4239. } else if (prim == NL_ROW) {
  4240. NLRowColumn* af = &context->af;
  4241. NLRowColumn* al = &context->al;
  4242. NLSparseMatrix* M = (NLSparseMatrix*)context->M;
  4243. double* b = context->b;
  4244. uint32_t nf = af->size;
  4245. uint32_t nl = al->size;
  4246. uint32_t n = context->n;
  4247. double S;
  4248. /*
  4249. * least_squares : we want to solve
  4250. * A'A x = A'b
  4251. */
  4252. for (uint32_t i = 0; i < nf; i++) {
  4253. for (uint32_t j = 0; j < nf; j++) {
  4254. nlSparseMatrixAdd(M, af->coeff[i].index, af->coeff[j].index, af->coeff[i].value * af->coeff[j].value);
  4255. }
  4256. }
  4257. for (uint32_t k = 0; k < context->nb_systems; ++k) {
  4258. S = 0.0;
  4259. for (uint32_t jj = 0; jj < nl; ++jj) {
  4260. uint32_t j = al->coeff[jj].index;
  4261. S += al->coeff[jj].value * NL_BUFFER_ITEM(context->variable_buffer[k], j);
  4262. }
  4263. for (uint32_t jj = 0; jj < nf; jj++)
  4264. b[k*n + af->coeff[jj].index] -= af->coeff[jj].value * S;
  4265. }
  4266. context->current_row++;
  4267. }
  4268. }
  4269. static bool nlSolve(NLContext *context)
  4270. {
  4271. nlDeleteMatrix(context->P);
  4272. context->P = nlNewJacobiPreconditioner(context->M);
  4273. nlMatrixCompress(&context->M);
  4274. bool result = nlSolveIterative(context);
  4275. nlVectorToVariables(context);
  4276. return result;
  4277. }
  4278. } // namespace opennl
  4279. namespace raster {
  4280. class ClippedTriangle
  4281. {
  4282. public:
  4283. ClippedTriangle(const Vector2 &a, const Vector2 &b, const Vector2 &c)
  4284. {
  4285. m_numVertices = 3;
  4286. m_activeVertexBuffer = 0;
  4287. m_verticesA[0] = a;
  4288. m_verticesA[1] = b;
  4289. m_verticesA[2] = c;
  4290. m_vertexBuffers[0] = m_verticesA;
  4291. m_vertexBuffers[1] = m_verticesB;
  4292. m_area = 0;
  4293. }
  4294. void clipHorizontalPlane(float offset, float clipdirection)
  4295. {
  4296. Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
  4297. m_activeVertexBuffer ^= 1;
  4298. Vector2 *v2 = m_vertexBuffers[m_activeVertexBuffer];
  4299. v[m_numVertices] = v[0];
  4300. float dy2, dy1 = offset - v[0].y;
  4301. int dy2in, dy1in = clipdirection * dy1 >= 0;
  4302. uint32_t p = 0;
  4303. for (uint32_t k = 0; k < m_numVertices; k++) {
  4304. dy2 = offset - v[k + 1].y;
  4305. dy2in = clipdirection * dy2 >= 0;
  4306. if (dy1in) v2[p++] = v[k];
  4307. if ( dy1in + dy2in == 1 ) { // not both in/out
  4308. float dx = v[k + 1].x - v[k].x;
  4309. float dy = v[k + 1].y - v[k].y;
  4310. v2[p++] = Vector2(v[k].x + dy1 * (dx / dy), offset);
  4311. }
  4312. dy1 = dy2;
  4313. dy1in = dy2in;
  4314. }
  4315. m_numVertices = p;
  4316. }
  4317. void clipVerticalPlane(float offset, float clipdirection)
  4318. {
  4319. Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
  4320. m_activeVertexBuffer ^= 1;
  4321. Vector2 *v2 = m_vertexBuffers[m_activeVertexBuffer];
  4322. v[m_numVertices] = v[0];
  4323. float dx2, dx1 = offset - v[0].x;
  4324. int dx2in, dx1in = clipdirection * dx1 >= 0;
  4325. uint32_t p = 0;
  4326. for (uint32_t k = 0; k < m_numVertices; k++) {
  4327. dx2 = offset - v[k + 1].x;
  4328. dx2in = clipdirection * dx2 >= 0;
  4329. if (dx1in) v2[p++] = v[k];
  4330. if ( dx1in + dx2in == 1 ) { // not both in/out
  4331. float dx = v[k + 1].x - v[k].x;
  4332. float dy = v[k + 1].y - v[k].y;
  4333. v2[p++] = Vector2(offset, v[k].y + dx1 * (dy / dx));
  4334. }
  4335. dx1 = dx2;
  4336. dx1in = dx2in;
  4337. }
  4338. m_numVertices = p;
  4339. }
  4340. void computeArea()
  4341. {
  4342. Vector2 *v = m_vertexBuffers[m_activeVertexBuffer];
  4343. v[m_numVertices] = v[0];
  4344. m_area = 0;
  4345. for (uint32_t k = 0; k < m_numVertices; k++) {
  4346. // http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
  4347. float f = v[k].x * v[k + 1].y - v[k + 1].x * v[k].y;
  4348. m_area += f;
  4349. }
  4350. m_area = 0.5f * fabsf(m_area);
  4351. }
  4352. void clipAABox(float x0, float y0, float x1, float y1)
  4353. {
  4354. clipVerticalPlane(x0, -1);
  4355. clipHorizontalPlane(y0, -1);
  4356. clipVerticalPlane(x1, 1);
  4357. clipHorizontalPlane(y1, 1);
  4358. computeArea();
  4359. }
  4360. float area() const
  4361. {
  4362. return m_area;
  4363. }
  4364. private:
  4365. Vector2 m_verticesA[7 + 1];
  4366. Vector2 m_verticesB[7 + 1];
  4367. Vector2 *m_vertexBuffers[2];
  4368. uint32_t m_numVertices;
  4369. uint32_t m_activeVertexBuffer;
  4370. float m_area;
  4371. };
  4372. /// A callback to sample the environment. Return false to terminate rasterization.
  4373. typedef bool (*SamplingCallback)(void *param, int x, int y);
  4374. /// A triangle for rasterization.
  4375. struct Triangle
  4376. {
  4377. Triangle(const Vector2 &_v0, const Vector2 &_v1, const Vector2 &_v2) : v1(_v0), v2(_v2), v3(_v1), n1(0.0f), n2(0.0f), n3(0.0f)
  4378. {
  4379. // make sure every triangle is front facing.
  4380. flipBackface();
  4381. // Compute deltas.
  4382. if (isValid())
  4383. computeUnitInwardNormals();
  4384. }
  4385. bool isValid()
  4386. {
  4387. const Vector2 e0 = v3 - v1;
  4388. const Vector2 e1 = v2 - v1;
  4389. const float area = e0.y * e1.x - e1.y * e0.x;
  4390. return area != 0.0f;
  4391. }
  4392. // extents has to be multiple of BK_SIZE!!
  4393. bool drawAA(const Vector2 &extents, SamplingCallback cb, void *param)
  4394. {
  4395. const float PX_INSIDE = 1.0f/sqrtf(2.0f);
  4396. const float PX_OUTSIDE = -1.0f/sqrtf(2.0f);
  4397. const float BK_SIZE = 8;
  4398. const float BK_INSIDE = sqrtf(BK_SIZE*BK_SIZE/2.0f);
  4399. const float BK_OUTSIDE = -sqrtf(BK_SIZE*BK_SIZE/2.0f);
  4400. // Bounding rectangle
  4401. float minx = floorf(max(min3(v1.x, v2.x, v3.x), 0.0f));
  4402. float miny = floorf(max(min3(v1.y, v2.y, v3.y), 0.0f));
  4403. float maxx = ceilf( min(max3(v1.x, v2.x, v3.x), extents.x - 1.0f));
  4404. float maxy = ceilf( min(max3(v1.y, v2.y, v3.y), extents.y - 1.0f));
  4405. // There's no reason to align the blocks to the viewport, instead we align them to the origin of the triangle bounds.
  4406. minx = floorf(minx);
  4407. miny = floorf(miny);
  4408. //minx = (float)(((int)minx) & (~((int)BK_SIZE - 1))); // align to blocksize (we don't need to worry about blocks partially out of viewport)
  4409. //miny = (float)(((int)miny) & (~((int)BK_SIZE - 1)));
  4410. minx += 0.5;
  4411. miny += 0.5; // sampling at texel centers!
  4412. maxx += 0.5;
  4413. maxy += 0.5;
  4414. // Half-edge constants
  4415. float C1 = n1.x * (-v1.x) + n1.y * (-v1.y);
  4416. float C2 = n2.x * (-v2.x) + n2.y * (-v2.y);
  4417. float C3 = n3.x * (-v3.x) + n3.y * (-v3.y);
  4418. // Loop through blocks
  4419. for (float y0 = miny; y0 <= maxy; y0 += BK_SIZE) {
  4420. for (float x0 = minx; x0 <= maxx; x0 += BK_SIZE) {
  4421. // Corners of block
  4422. float xc = (x0 + (BK_SIZE - 1) / 2.0f);
  4423. float yc = (y0 + (BK_SIZE - 1) / 2.0f);
  4424. // Evaluate half-space functions
  4425. float aC = C1 + n1.x * xc + n1.y * yc;
  4426. float bC = C2 + n2.x * xc + n2.y * yc;
  4427. float cC = C3 + n3.x * xc + n3.y * yc;
  4428. // Skip block when outside an edge
  4429. if ( (aC <= BK_OUTSIDE) || (bC <= BK_OUTSIDE) || (cC <= BK_OUTSIDE) ) continue;
  4430. // Accept whole block when totally covered
  4431. if ( (aC >= BK_INSIDE) && (bC >= BK_INSIDE) && (cC >= BK_INSIDE) ) {
  4432. for (float y = y0; y < y0 + BK_SIZE; y++) {
  4433. for (float x = x0; x < x0 + BK_SIZE; x++) {
  4434. if (!cb(param, (int)x, (int)y))
  4435. return false;
  4436. }
  4437. }
  4438. } else { // Partially covered block
  4439. float CY1 = C1 + n1.x * x0 + n1.y * y0;
  4440. float CY2 = C2 + n2.x * x0 + n2.y * y0;
  4441. float CY3 = C3 + n3.x * x0 + n3.y * y0;
  4442. for (float y = y0; y < y0 + BK_SIZE; y++) { // @@ This is not clipping to scissor rectangle correctly.
  4443. float CX1 = CY1;
  4444. float CX2 = CY2;
  4445. float CX3 = CY3;
  4446. for (float x = x0; x < x0 + BK_SIZE; x++) { // @@ This is not clipping to scissor rectangle correctly.
  4447. if (CX1 >= PX_INSIDE && CX2 >= PX_INSIDE && CX3 >= PX_INSIDE) {
  4448. if (!cb(param, (int)x, (int)y))
  4449. return false;
  4450. } else if ((CX1 >= PX_OUTSIDE) && (CX2 >= PX_OUTSIDE) && (CX3 >= PX_OUTSIDE)) {
  4451. // triangle partially covers pixel. do clipping.
  4452. ClippedTriangle ct(v1 - Vector2(x, y), v2 - Vector2(x, y), v3 - Vector2(x, y));
  4453. ct.clipAABox(-0.5, -0.5, 0.5, 0.5);
  4454. if (ct.area() > 0.0f) {
  4455. if (!cb(param, (int)x, (int)y))
  4456. return false;
  4457. }
  4458. }
  4459. CX1 += n1.x;
  4460. CX2 += n2.x;
  4461. CX3 += n3.x;
  4462. }
  4463. CY1 += n1.y;
  4464. CY2 += n2.y;
  4465. CY3 += n3.y;
  4466. }
  4467. }
  4468. }
  4469. }
  4470. return true;
  4471. }
  4472. private:
  4473. void flipBackface()
  4474. {
  4475. // check if triangle is backfacing, if so, swap two vertices
  4476. if ( ((v3.x - v1.x) * (v2.y - v1.y) - (v3.y - v1.y) * (v2.x - v1.x)) < 0 ) {
  4477. Vector2 hv = v1;
  4478. v1 = v2;
  4479. v2 = hv; // swap pos
  4480. }
  4481. }
  4482. // compute unit inward normals for each edge.
  4483. void computeUnitInwardNormals()
  4484. {
  4485. n1 = v1 - v2;
  4486. n1 = Vector2(-n1.y, n1.x);
  4487. n1 = n1 * (1.0f / sqrtf(dot(n1, n1)));
  4488. n2 = v2 - v3;
  4489. n2 = Vector2(-n2.y, n2.x);
  4490. n2 = n2 * (1.0f / sqrtf(dot(n2, n2)));
  4491. n3 = v3 - v1;
  4492. n3 = Vector2(-n3.y, n3.x);
  4493. n3 = n3 * (1.0f / sqrtf(dot(n3, n3)));
  4494. }
  4495. // Vertices.
  4496. Vector2 v1, v2, v3;
  4497. Vector2 n1, n2, n3; // unit inward normals
  4498. };
  4499. // Process the given triangle. Returns false if rasterization was interrupted by the callback.
  4500. static bool drawTriangle(const Vector2 &extents, const Vector2 v[3], SamplingCallback cb, void *param)
  4501. {
  4502. Triangle tri(v[0], v[1], v[2]);
  4503. // @@ It would be nice to have a conservative drawing mode that enlarges the triangle extents by one texel and is able to handle degenerate triangles.
  4504. // @@ Maybe the simplest thing to do would be raster triangle edges.
  4505. if (tri.isValid())
  4506. return tri.drawAA(extents, cb, param);
  4507. return true;
  4508. }
  4509. } // namespace raster
  4510. namespace segment {
  4511. // - Insertion is o(n)
  4512. // - Smallest element goes at the end, so that popping it is o(1).
  4513. struct CostQueue
  4514. {
  4515. CostQueue(uint32_t size = UINT32_MAX) : m_maxSize(size), m_pairs(MemTag::SegmentAtlasChartCandidates) {}
  4516. float peekCost() const
  4517. {
  4518. return m_pairs.back().cost;
  4519. }
  4520. uint32_t peekFace() const
  4521. {
  4522. return m_pairs.back().face;
  4523. }
  4524. void push(float cost, uint32_t face)
  4525. {
  4526. const Pair p = { cost, face };
  4527. if (m_pairs.isEmpty() || cost < peekCost())
  4528. m_pairs.push_back(p);
  4529. else {
  4530. uint32_t i = 0;
  4531. const uint32_t count = m_pairs.size();
  4532. for (; i < count; i++) {
  4533. if (m_pairs[i].cost < cost)
  4534. break;
  4535. }
  4536. m_pairs.insertAt(i, p);
  4537. if (m_pairs.size() > m_maxSize)
  4538. m_pairs.removeAt(0);
  4539. }
  4540. }
  4541. uint32_t pop()
  4542. {
  4543. XA_DEBUG_ASSERT(!m_pairs.isEmpty());
  4544. uint32_t f = m_pairs.back().face;
  4545. m_pairs.pop_back();
  4546. return f;
  4547. }
  4548. XA_INLINE void clear()
  4549. {
  4550. m_pairs.clear();
  4551. }
  4552. XA_INLINE uint32_t count() const
  4553. {
  4554. return m_pairs.size();
  4555. }
  4556. private:
  4557. const uint32_t m_maxSize;
  4558. struct Pair
  4559. {
  4560. float cost;
  4561. uint32_t face;
  4562. };
  4563. Array<Pair> m_pairs;
  4564. };
  4565. struct AtlasData
  4566. {
  4567. ChartOptions options;
  4568. const Mesh *mesh = nullptr;
  4569. Array<float> edgeDihedralAngles;
  4570. Array<float> edgeLengths;
  4571. Array<float> faceAreas;
  4572. Array<float> faceUvAreas; // Can be negative.
  4573. Array<Vector3> faceNormals;
  4574. BitArray isFaceInChart;
  4575. AtlasData() : edgeDihedralAngles(MemTag::SegmentAtlasMeshData), edgeLengths(MemTag::SegmentAtlasMeshData), faceAreas(MemTag::SegmentAtlasMeshData), faceNormals(MemTag::SegmentAtlasMeshData) {}
  4576. void compute()
  4577. {
  4578. const uint32_t faceCount = mesh->faceCount();
  4579. const uint32_t edgeCount = mesh->edgeCount();
  4580. edgeDihedralAngles.resize(edgeCount);
  4581. edgeLengths.resize(edgeCount);
  4582. faceAreas.resize(faceCount);
  4583. if (options.useInputMeshUvs)
  4584. faceUvAreas.resize(faceCount);
  4585. faceNormals.resize(faceCount);
  4586. isFaceInChart.resize(faceCount);
  4587. isFaceInChart.zeroOutMemory();
  4588. for (uint32_t f = 0; f < faceCount; f++) {
  4589. for (uint32_t i = 0; i < 3; i++) {
  4590. const uint32_t edge = f * 3 + i;
  4591. const Vector3 &p0 = mesh->position(mesh->vertexAt(meshEdgeIndex0(edge)));
  4592. const Vector3 &p1 = mesh->position(mesh->vertexAt(meshEdgeIndex1(edge)));
  4593. edgeLengths[edge] = length(p1 - p0);
  4594. XA_DEBUG_ASSERT(edgeLengths[edge] > 0.0f);
  4595. }
  4596. faceAreas[f] = mesh->computeFaceArea(f);
  4597. XA_DEBUG_ASSERT(faceAreas[f] > 0.0f);
  4598. if (options.useInputMeshUvs)
  4599. faceUvAreas[f] = mesh->computeFaceParametricArea(f);
  4600. faceNormals[f] = mesh->computeFaceNormal(f);
  4601. }
  4602. for (uint32_t face = 0; face < faceCount; face++) {
  4603. for (uint32_t i = 0; i < 3; i++) {
  4604. const uint32_t edge = face * 3 + i;
  4605. const uint32_t oedge = mesh->oppositeEdge(edge);
  4606. if (oedge == UINT32_MAX)
  4607. edgeDihedralAngles[edge] = FLT_MAX;
  4608. else {
  4609. const uint32_t oface = meshEdgeFace(oedge);
  4610. edgeDihedralAngles[edge] = edgeDihedralAngles[oedge] = dot(faceNormals[face], faceNormals[oface]);
  4611. }
  4612. }
  4613. }
  4614. }
  4615. };
  4616. // If MeshDecl::vertexUvData is set on input meshes, find charts by floodfilling faces in world/model space without crossing UV seams.
  4617. struct OriginalUvCharts
  4618. {
  4619. OriginalUvCharts(AtlasData &data) : m_data(data) {}
  4620. uint32_t chartCount() const { return m_charts.size(); }
  4621. const Basis &chartBasis(uint32_t chartIndex) const { return m_chartBasis[chartIndex]; }
  4622. ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const
  4623. {
  4624. const Chart &chart = m_charts[chartIndex];
  4625. return ConstArrayView<uint32_t>(&m_chartFaces[chart.firstFace], chart.faceCount);
  4626. }
  4627. void compute()
  4628. {
  4629. m_charts.clear();
  4630. m_chartFaces.clear();
  4631. const Mesh *mesh = m_data.mesh;
  4632. const uint32_t faceCount = mesh->faceCount();
  4633. for (uint32_t f = 0; f < faceCount; f++) {
  4634. if (m_data.isFaceInChart.get(f))
  4635. continue;
  4636. if (isZero(m_data.faceUvAreas[f], kAreaEpsilon))
  4637. continue; // Face must have valid UVs.
  4638. // Found an unassigned face, create a new chart.
  4639. Chart chart;
  4640. chart.firstFace = m_chartFaces.size();
  4641. chart.faceCount = 1;
  4642. m_chartFaces.push_back(f);
  4643. m_data.isFaceInChart.set(f);
  4644. floodfillFaces(chart);
  4645. m_charts.push_back(chart);
  4646. }
  4647. // Compute basis for each chart.
  4648. m_chartBasis.resize(m_charts.size());
  4649. for (uint32_t c = 0; c < m_charts.size(); c++)
  4650. {
  4651. const Chart &chart = m_charts[c];
  4652. m_tempPoints.resize(chart.faceCount * 3);
  4653. for (uint32_t f = 0; f < chart.faceCount; f++) {
  4654. const uint32_t face = m_chartFaces[chart.firstFace + f];
  4655. for (uint32_t i = 0; i < 3; i++)
  4656. m_tempPoints[f * 3 + i] = m_data.mesh->position(m_data.mesh->vertexAt(face * 3 + i));
  4657. }
  4658. Fit::computeBasis(m_tempPoints, &m_chartBasis[c]);
  4659. }
  4660. }
  4661. private:
  4662. struct Chart
  4663. {
  4664. uint32_t firstFace, faceCount;
  4665. };
  4666. void floodfillFaces(Chart &chart)
  4667. {
  4668. const bool isFaceAreaNegative = m_data.faceUvAreas[m_chartFaces[chart.firstFace]] < 0.0f;
  4669. for (;;) {
  4670. bool newFaceAdded = false;
  4671. const uint32_t faceCount = chart.faceCount;
  4672. for (uint32_t f = 0; f < faceCount; f++) {
  4673. const uint32_t sourceFace = m_chartFaces[chart.firstFace + f];
  4674. for (Mesh::FaceEdgeIterator edgeIt(m_data.mesh, sourceFace); !edgeIt.isDone(); edgeIt.advance()) {
  4675. const uint32_t face = edgeIt.oppositeFace();
  4676. if (face == UINT32_MAX)
  4677. continue; // Boundary edge.
  4678. if (m_data.isFaceInChart.get(face))
  4679. continue; // Already assigned to a chart.
  4680. if (isZero(m_data.faceUvAreas[face], kAreaEpsilon))
  4681. continue; // Face must have valid UVs.
  4682. if ((m_data.faceUvAreas[face] < 0.0f) != isFaceAreaNegative)
  4683. continue; // Face winding is opposite of the first chart face.
  4684. const Vector2 &uv0 = m_data.mesh->texcoord(edgeIt.vertex0());
  4685. const Vector2 &uv1 = m_data.mesh->texcoord(edgeIt.vertex1());
  4686. const Vector2 &ouv0 = m_data.mesh->texcoord(m_data.mesh->vertexAt(meshEdgeIndex0(edgeIt.oppositeEdge())));
  4687. const Vector2 &ouv1 = m_data.mesh->texcoord(m_data.mesh->vertexAt(meshEdgeIndex1(edgeIt.oppositeEdge())));
  4688. if (!equal(uv0, ouv1, m_data.mesh->epsilon()) || !equal(uv1, ouv0, m_data.mesh->epsilon()))
  4689. continue; // UVs must match exactly.
  4690. m_chartFaces.push_back(face);
  4691. chart.faceCount++;
  4692. m_data.isFaceInChart.set(face);
  4693. newFaceAdded = true;
  4694. }
  4695. }
  4696. if (!newFaceAdded)
  4697. break;
  4698. }
  4699. }
  4700. AtlasData &m_data;
  4701. Array<Chart> m_charts;
  4702. Array<Basis> m_chartBasis;
  4703. Array<uint32_t> m_chartFaces;
  4704. Array<Vector3> m_tempPoints;
  4705. };
  4706. #if XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS
  4707. static uint32_t s_planarRegionsCurrentRegion;
  4708. static uint32_t s_planarRegionsCurrentVertex;
  4709. #endif
  4710. struct PlanarCharts
  4711. {
  4712. PlanarCharts(AtlasData &data) : m_data(data), m_nextRegionFace(MemTag::SegmentAtlasPlanarRegions), m_faceToRegionId(MemTag::SegmentAtlasPlanarRegions) {}
  4713. const Basis &chartBasis(uint32_t chartIndex) const { return m_chartBasis[chartIndex]; }
  4714. uint32_t chartCount() const { return m_charts.size(); }
  4715. ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const
  4716. {
  4717. const Chart &chart = m_charts[chartIndex];
  4718. return ConstArrayView<uint32_t>(&m_chartFaces[chart.firstFace], chart.faceCount);
  4719. }
  4720. uint32_t regionIdFromFace(uint32_t face) const { return m_faceToRegionId[face]; }
  4721. uint32_t nextRegionFace(uint32_t face) const { return m_nextRegionFace[face]; }
  4722. float regionArea(uint32_t region) const { return m_regionAreas[region]; }
  4723. void compute()
  4724. {
  4725. const uint32_t faceCount = m_data.mesh->faceCount();
  4726. // Precompute regions of coplanar incident faces.
  4727. m_regionFirstFace.clear();
  4728. m_nextRegionFace.resize(faceCount);
  4729. m_faceToRegionId.resize(faceCount);
  4730. for (uint32_t f = 0; f < faceCount; f++) {
  4731. m_nextRegionFace[f] = f;
  4732. m_faceToRegionId[f] = UINT32_MAX;
  4733. }
  4734. Array<uint32_t> faceStack;
  4735. faceStack.reserve(min(faceCount, 16u));
  4736. uint32_t regionCount = 0;
  4737. for (uint32_t f = 0; f < faceCount; f++) {
  4738. if (m_nextRegionFace[f] != f)
  4739. continue; // Already assigned.
  4740. if (m_data.isFaceInChart.get(f))
  4741. continue; // Already in a chart.
  4742. faceStack.clear();
  4743. faceStack.push_back(f);
  4744. for (;;) {
  4745. if (faceStack.isEmpty())
  4746. break;
  4747. const uint32_t face = faceStack.back();
  4748. m_faceToRegionId[face] = regionCount;
  4749. faceStack.pop_back();
  4750. for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
  4751. const uint32_t oface = it.oppositeFace();
  4752. if (it.isBoundary())
  4753. continue;
  4754. if (m_nextRegionFace[oface] != oface)
  4755. continue; // Already assigned.
  4756. if (m_data.isFaceInChart.get(oface))
  4757. continue; // Already in a chart.
  4758. if (!equal(dot(m_data.faceNormals[face], m_data.faceNormals[oface]), 1.0f, kEpsilon))
  4759. continue; // Not coplanar.
  4760. const uint32_t next = m_nextRegionFace[face];
  4761. m_nextRegionFace[face] = oface;
  4762. m_nextRegionFace[oface] = next;
  4763. m_faceToRegionId[oface] = regionCount;
  4764. faceStack.push_back(oface);
  4765. }
  4766. }
  4767. m_regionFirstFace.push_back(f);
  4768. regionCount++;
  4769. }
  4770. #if XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS
  4771. static std::mutex s_mutex;
  4772. {
  4773. std::lock_guard<std::mutex> lock(s_mutex);
  4774. FILE *file;
  4775. XA_FOPEN(file, "debug_mesh_planar_regions.obj", s_planarRegionsCurrentRegion == 0 ? "w" : "a");
  4776. if (file) {
  4777. m_data.mesh->writeObjVertices(file);
  4778. fprintf(file, "s off\n");
  4779. for (uint32_t i = 0; i < regionCount; i++) {
  4780. fprintf(file, "o region%u\n", s_planarRegionsCurrentRegion);
  4781. for (uint32_t j = 0; j < faceCount; j++) {
  4782. if (m_faceToRegionId[j] == i)
  4783. m_data.mesh->writeObjFace(file, j, s_planarRegionsCurrentVertex);
  4784. }
  4785. s_planarRegionsCurrentRegion++;
  4786. }
  4787. s_planarRegionsCurrentVertex += m_data.mesh->vertexCount();
  4788. fclose(file);
  4789. }
  4790. }
  4791. #endif
  4792. // Precompute planar region areas.
  4793. m_regionAreas.resize(regionCount);
  4794. m_regionAreas.zeroOutMemory();
  4795. for (uint32_t f = 0; f < faceCount; f++) {
  4796. if (m_faceToRegionId[f] == UINT32_MAX)
  4797. continue;
  4798. m_regionAreas[m_faceToRegionId[f]] += m_data.faceAreas[f];
  4799. }
  4800. // Create charts from suitable planar regions.
  4801. // The dihedral angle of all boundary edges must be >= 90 degrees.
  4802. m_charts.clear();
  4803. m_chartFaces.clear();
  4804. for (uint32_t region = 0; region < regionCount; region++) {
  4805. const uint32_t firstRegionFace = m_regionFirstFace[region];
  4806. uint32_t face = firstRegionFace;
  4807. bool createChart = true;
  4808. do {
  4809. for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
  4810. if (it.isBoundary())
  4811. continue; // Ignore mesh boundary edges.
  4812. const uint32_t oface = it.oppositeFace();
  4813. if (m_faceToRegionId[oface] == region)
  4814. continue; // Ignore internal edges.
  4815. const float angle = m_data.edgeDihedralAngles[it.edge()];
  4816. if (angle > 0.0f && angle < FLT_MAX) { // FLT_MAX on boundaries.
  4817. createChart = false;
  4818. break;
  4819. }
  4820. }
  4821. if (!createChart)
  4822. break;
  4823. face = m_nextRegionFace[face];
  4824. }
  4825. while (face != firstRegionFace);
  4826. // Create a chart.
  4827. if (createChart) {
  4828. Chart chart;
  4829. chart.firstFace = m_chartFaces.size();
  4830. chart.faceCount = 0;
  4831. face = firstRegionFace;
  4832. do {
  4833. m_data.isFaceInChart.set(face);
  4834. m_chartFaces.push_back(face);
  4835. chart.faceCount++;
  4836. face = m_nextRegionFace[face];
  4837. }
  4838. while (face != firstRegionFace);
  4839. m_charts.push_back(chart);
  4840. }
  4841. }
  4842. // Compute basis for each chart using the first face normal (all faces have the same normal).
  4843. m_chartBasis.resize(m_charts.size());
  4844. for (uint32_t c = 0; c < m_charts.size(); c++)
  4845. {
  4846. const uint32_t face = m_chartFaces[m_charts[c].firstFace];
  4847. Basis &basis = m_chartBasis[c];
  4848. basis.normal = m_data.faceNormals[face];
  4849. basis.tangent = Basis::computeTangent(basis.normal);
  4850. basis.bitangent = Basis::computeBitangent(basis.normal, basis.tangent);
  4851. }
  4852. }
  4853. private:
  4854. struct Chart
  4855. {
  4856. uint32_t firstFace, faceCount;
  4857. };
  4858. AtlasData &m_data;
  4859. Array<uint32_t> m_regionFirstFace;
  4860. Array<uint32_t> m_nextRegionFace;
  4861. Array<uint32_t> m_faceToRegionId;
  4862. Array<float> m_regionAreas;
  4863. Array<Chart> m_charts;
  4864. Array<uint32_t> m_chartFaces;
  4865. Array<Basis> m_chartBasis;
  4866. };
  4867. struct ClusteredCharts
  4868. {
  4869. ClusteredCharts(AtlasData &data, const PlanarCharts &planarCharts) : m_data(data), m_planarCharts(planarCharts), m_texcoords(MemTag::SegmentAtlasMeshData), m_bestTriangles(10), m_placingSeeds(false) {}
  4870. ~ClusteredCharts()
  4871. {
  4872. const uint32_t chartCount = m_charts.size();
  4873. for (uint32_t i = 0; i < chartCount; i++) {
  4874. m_charts[i]->~Chart();
  4875. XA_FREE(m_charts[i]);
  4876. }
  4877. }
  4878. uint32_t chartCount() const { return m_charts.size(); }
  4879. ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const { return m_charts[chartIndex]->faces; }
  4880. const Basis &chartBasis(uint32_t chartIndex) const { return m_charts[chartIndex]->basis; }
  4881. void compute()
  4882. {
  4883. const uint32_t faceCount = m_data.mesh->faceCount();
  4884. m_facesLeft = 0;
  4885. for (uint32_t i = 0; i < faceCount; i++) {
  4886. if (!m_data.isFaceInChart.get(i))
  4887. m_facesLeft++;
  4888. }
  4889. const uint32_t chartCount = m_charts.size();
  4890. for (uint32_t i = 0; i < chartCount; i++) {
  4891. m_charts[i]->~Chart();
  4892. XA_FREE(m_charts[i]);
  4893. }
  4894. m_charts.clear();
  4895. m_faceCharts.resize(faceCount);
  4896. m_faceCharts.fill(-1);
  4897. m_texcoords.resize(faceCount * 3);
  4898. if (m_facesLeft == 0)
  4899. return;
  4900. // Create initial charts greedely.
  4901. placeSeeds(m_data.options.maxCost * 0.5f);
  4902. if (m_data.options.maxIterations == 0) {
  4903. XA_DEBUG_ASSERT(m_facesLeft == 0);
  4904. return;
  4905. }
  4906. relocateSeeds();
  4907. resetCharts();
  4908. // Restart process growing charts in parallel.
  4909. uint32_t iteration = 0;
  4910. for (;;) {
  4911. growCharts(m_data.options.maxCost);
  4912. // When charts cannot grow more: fill holes, merge charts, relocate seeds and start new iteration.
  4913. fillHoles(m_data.options.maxCost * 0.5f);
  4914. #if XA_MERGE_CHARTS
  4915. mergeCharts();
  4916. #endif
  4917. if (++iteration == m_data.options.maxIterations)
  4918. break;
  4919. if (!relocateSeeds())
  4920. break;
  4921. resetCharts();
  4922. }
  4923. // Make sure no holes are left!
  4924. XA_DEBUG_ASSERT(m_facesLeft == 0);
  4925. }
  4926. private:
  4927. struct Chart
  4928. {
  4929. Chart() : faces(MemTag::SegmentAtlasChartFaces) {}
  4930. int id = -1;
  4931. Basis basis; // Best fit normal.
  4932. float area = 0.0f;
  4933. float boundaryLength = 0.0f;
  4934. Vector3 centroidSum = Vector3(0.0f); // Sum of chart face centroids.
  4935. Vector3 centroid = Vector3(0.0f); // Average centroid of chart faces.
  4936. Array<uint32_t> faces;
  4937. Array<uint32_t> failedPlanarRegions;
  4938. CostQueue candidates;
  4939. uint32_t seed;
  4940. };
  4941. void placeSeeds(float threshold)
  4942. {
  4943. XA_PROFILE_START(clusteredChartsPlaceSeeds)
  4944. m_placingSeeds = true;
  4945. // Instead of using a predefiened number of seeds:
  4946. // - Add seeds one by one, growing chart until a certain treshold.
  4947. // - Undo charts and restart growing process.
  4948. // @@ How can we give preference to faces far from sharp features as in the LSCM paper?
  4949. // - those points can be found using a simple flood filling algorithm.
  4950. // - how do we weight the probabilities?
  4951. while (m_facesLeft > 0)
  4952. createChart(threshold);
  4953. m_placingSeeds = false;
  4954. XA_PROFILE_END(clusteredChartsPlaceSeeds)
  4955. }
  4956. // Returns true if any of the charts can grow more.
  4957. void growCharts(float threshold)
  4958. {
  4959. XA_PROFILE_START(clusteredChartsGrow)
  4960. for (;;) {
  4961. if (m_facesLeft == 0)
  4962. break;
  4963. // Get the single best candidate out of the chart best candidates.
  4964. uint32_t bestFace = UINT32_MAX, bestChart = UINT32_MAX;
  4965. float lowestCost = FLT_MAX;
  4966. for (uint32_t i = 0; i < m_charts.size(); i++) {
  4967. Chart *chart = m_charts[i];
  4968. // Get the best candidate from the chart.
  4969. // Cleanup any best candidates that have been claimed by another chart.
  4970. uint32_t face = UINT32_MAX;
  4971. float cost = FLT_MAX;
  4972. for (;;) {
  4973. if (chart->candidates.count() == 0)
  4974. break;
  4975. cost = chart->candidates.peekCost();
  4976. face = chart->candidates.peekFace();
  4977. if (!m_data.isFaceInChart.get(face))
  4978. break;
  4979. else {
  4980. // Face belongs to another chart. Pop from queue so the next best candidate can be retrieved.
  4981. chart->candidates.pop();
  4982. face = UINT32_MAX;
  4983. }
  4984. }
  4985. if (face == UINT32_MAX)
  4986. continue; // No candidates for this chart.
  4987. // See if best candidate overall.
  4988. if (cost < lowestCost) {
  4989. lowestCost = cost;
  4990. bestFace = face;
  4991. bestChart = i;
  4992. }
  4993. }
  4994. if (bestFace == UINT32_MAX || lowestCost > threshold)
  4995. break;
  4996. Chart *chart = m_charts[bestChart];
  4997. chart->candidates.pop(); // Pop the selected candidate from the queue.
  4998. if (!addFaceToChart(chart, bestFace))
  4999. chart->failedPlanarRegions.push_back(m_planarCharts.regionIdFromFace(bestFace));
  5000. }
  5001. XA_PROFILE_END(clusteredChartsGrow)
  5002. }
  5003. void resetCharts()
  5004. {
  5005. XA_PROFILE_START(clusteredChartsReset)
  5006. const uint32_t faceCount = m_data.mesh->faceCount();
  5007. for (uint32_t i = 0; i < faceCount; i++) {
  5008. if (m_faceCharts[i] != -1)
  5009. m_data.isFaceInChart.unset(i);
  5010. m_faceCharts[i] = -1;
  5011. }
  5012. m_facesLeft = 0;
  5013. for (uint32_t i = 0; i < faceCount; i++) {
  5014. if (!m_data.isFaceInChart.get(i))
  5015. m_facesLeft++;
  5016. }
  5017. const uint32_t chartCount = m_charts.size();
  5018. for (uint32_t i = 0; i < chartCount; i++) {
  5019. Chart *chart = m_charts[i];
  5020. chart->area = 0.0f;
  5021. chart->boundaryLength = 0.0f;
  5022. chart->basis.normal = Vector3(0.0f);
  5023. chart->basis.tangent = Vector3(0.0f);
  5024. chart->basis.bitangent = Vector3(0.0f);
  5025. chart->centroidSum = Vector3(0.0f);
  5026. chart->centroid = Vector3(0.0f);
  5027. chart->faces.clear();
  5028. chart->candidates.clear();
  5029. chart->failedPlanarRegions.clear();
  5030. addFaceToChart(chart, chart->seed);
  5031. }
  5032. XA_PROFILE_END(clusteredChartsReset)
  5033. }
  5034. bool relocateSeeds()
  5035. {
  5036. XA_PROFILE_START(clusteredChartsRelocateSeeds)
  5037. bool anySeedChanged = false;
  5038. const uint32_t chartCount = m_charts.size();
  5039. for (uint32_t i = 0; i < chartCount; i++) {
  5040. if (relocateSeed(m_charts[i])) {
  5041. anySeedChanged = true;
  5042. }
  5043. }
  5044. XA_PROFILE_END(clusteredChartsRelocateSeeds)
  5045. return anySeedChanged;
  5046. }
  5047. void fillHoles(float threshold)
  5048. {
  5049. XA_PROFILE_START(clusteredChartsFillHoles)
  5050. while (m_facesLeft > 0)
  5051. createChart(threshold);
  5052. XA_PROFILE_END(clusteredChartsFillHoles)
  5053. }
  5054. #if XA_MERGE_CHARTS
  5055. void mergeCharts()
  5056. {
  5057. XA_PROFILE_START(clusteredChartsMerge)
  5058. const uint32_t chartCount = m_charts.size();
  5059. // Merge charts progressively until there's none left to merge.
  5060. for (;;) {
  5061. bool merged = false;
  5062. for (int c = chartCount - 1; c >= 0; c--) {
  5063. Chart *chart = m_charts[c];
  5064. if (chart == nullptr)
  5065. continue;
  5066. float externalBoundaryLength = 0.0f;
  5067. m_sharedBoundaryLengths.resize(chartCount);
  5068. m_sharedBoundaryLengths.zeroOutMemory();
  5069. m_sharedBoundaryLengthsNoSeams.resize(chartCount);
  5070. m_sharedBoundaryLengthsNoSeams.zeroOutMemory();
  5071. m_sharedBoundaryEdgeCountNoSeams.resize(chartCount);
  5072. m_sharedBoundaryEdgeCountNoSeams.zeroOutMemory();
  5073. const uint32_t faceCount = chart->faces.size();
  5074. for (uint32_t i = 0; i < faceCount; i++) {
  5075. const uint32_t f = chart->faces[i];
  5076. for (Mesh::FaceEdgeIterator it(m_data.mesh, f); !it.isDone(); it.advance()) {
  5077. const float l = m_data.edgeLengths[it.edge()];
  5078. if (it.isBoundary()) {
  5079. externalBoundaryLength += l;
  5080. } else {
  5081. const int neighborChart = m_faceCharts[it.oppositeFace()];
  5082. if (neighborChart == -1)
  5083. externalBoundaryLength += l;
  5084. else if (m_charts[neighborChart] != chart) {
  5085. if ((it.isSeam() && (isNormalSeam(it.edge()) || it.isTextureSeam()))) {
  5086. externalBoundaryLength += l;
  5087. } else {
  5088. m_sharedBoundaryLengths[neighborChart] += l;
  5089. }
  5090. m_sharedBoundaryLengthsNoSeams[neighborChart] += l;
  5091. m_sharedBoundaryEdgeCountNoSeams[neighborChart]++;
  5092. }
  5093. }
  5094. }
  5095. }
  5096. for (int cc = chartCount - 1; cc >= 0; cc--) {
  5097. if (cc == c)
  5098. continue;
  5099. Chart *chart2 = m_charts[cc];
  5100. if (chart2 == nullptr)
  5101. continue;
  5102. // Must share a boundary.
  5103. if (m_sharedBoundaryLengths[cc] <= 0.0f)
  5104. continue;
  5105. // Compare proxies.
  5106. if (dot(chart2->basis.normal, chart->basis.normal) < XA_MERGE_CHARTS_MIN_NORMAL_DEVIATION)
  5107. continue;
  5108. // Obey max chart area and boundary length.
  5109. if (m_data.options.maxChartArea > 0.0f && chart->area + chart2->area > m_data.options.maxChartArea)
  5110. continue;
  5111. if (m_data.options.maxBoundaryLength > 0.0f && chart->boundaryLength + chart2->boundaryLength - m_sharedBoundaryLengthsNoSeams[cc] > m_data.options.maxBoundaryLength)
  5112. continue;
  5113. // Merge if chart2 has a single face.
  5114. // chart1 must have more than 1 face.
  5115. // chart2 area must be <= 10% of chart1 area.
  5116. if (m_sharedBoundaryLengthsNoSeams[cc] > 0.0f && chart->faces.size() > 1 && chart2->faces.size() == 1 && chart2->area <= chart->area * 0.1f)
  5117. goto merge;
  5118. // Merge if chart2 has two faces (probably a quad), and chart1 bounds at least 2 of its edges.
  5119. if (chart2->faces.size() == 2 && m_sharedBoundaryEdgeCountNoSeams[cc] >= 2)
  5120. goto merge;
  5121. // Merge if chart2 is wholely inside chart1, ignoring seams.
  5122. if (m_sharedBoundaryLengthsNoSeams[cc] > 0.0f && equal(m_sharedBoundaryLengthsNoSeams[cc], chart2->boundaryLength, kEpsilon))
  5123. goto merge;
  5124. if (m_sharedBoundaryLengths[cc] > 0.2f * max(0.0f, chart->boundaryLength - externalBoundaryLength) ||
  5125. m_sharedBoundaryLengths[cc] > 0.75f * chart2->boundaryLength)
  5126. goto merge;
  5127. continue;
  5128. merge:
  5129. if (!mergeChart(chart, chart2, m_sharedBoundaryLengthsNoSeams[cc]))
  5130. continue;
  5131. merged = true;
  5132. break;
  5133. }
  5134. if (merged)
  5135. break;
  5136. }
  5137. if (!merged)
  5138. break;
  5139. }
  5140. // Remove deleted charts.
  5141. for (int c = 0; c < int32_t(m_charts.size()); /*do not increment if removed*/) {
  5142. if (m_charts[c] == nullptr) {
  5143. m_charts.removeAt(c);
  5144. // Update m_faceCharts.
  5145. const uint32_t faceCount = m_faceCharts.size();
  5146. for (uint32_t i = 0; i < faceCount; i++) {
  5147. XA_DEBUG_ASSERT(m_faceCharts[i] != c);
  5148. XA_DEBUG_ASSERT(m_faceCharts[i] <= int32_t(m_charts.size()));
  5149. if (m_faceCharts[i] > c) {
  5150. m_faceCharts[i]--;
  5151. }
  5152. }
  5153. } else {
  5154. m_charts[c]->id = c;
  5155. c++;
  5156. }
  5157. }
  5158. XA_PROFILE_END(clusteredChartsMerge)
  5159. }
  5160. #endif
  5161. private:
  5162. void createChart(float threshold)
  5163. {
  5164. Chart *chart = XA_NEW(MemTag::Default, Chart);
  5165. chart->id = (int)m_charts.size();
  5166. m_charts.push_back(chart);
  5167. // Pick a face not used by any chart yet, belonging to the largest planar region.
  5168. chart->seed = 0;
  5169. float largestArea = 0.0f;
  5170. for (uint32_t f = 0; f < m_data.mesh->faceCount(); f++) {
  5171. if (m_data.isFaceInChart.get(f))
  5172. continue;
  5173. const float area = m_planarCharts.regionArea(m_planarCharts.regionIdFromFace(f));
  5174. if (area > largestArea) {
  5175. largestArea = area;
  5176. chart->seed = f;
  5177. }
  5178. }
  5179. addFaceToChart(chart, chart->seed);
  5180. // Grow the chart as much as possible within the given threshold.
  5181. for (;;) {
  5182. if (chart->candidates.count() == 0 || chart->candidates.peekCost() > threshold)
  5183. break;
  5184. const uint32_t f = chart->candidates.pop();
  5185. if (m_data.isFaceInChart.get(f))
  5186. continue;
  5187. if (!addFaceToChart(chart, f)) {
  5188. chart->failedPlanarRegions.push_back(m_planarCharts.regionIdFromFace(f));
  5189. continue;
  5190. }
  5191. }
  5192. }
  5193. bool isChartBoundaryEdge(const Chart *chart, uint32_t edge) const
  5194. {
  5195. const uint32_t oppositeEdge = m_data.mesh->oppositeEdge(edge);
  5196. const uint32_t oppositeFace = meshEdgeFace(oppositeEdge);
  5197. return oppositeEdge == UINT32_MAX || m_faceCharts[oppositeFace] != chart->id;
  5198. }
  5199. bool computeChartBasis(Chart *chart, Basis *basis)
  5200. {
  5201. const uint32_t faceCount = chart->faces.size();
  5202. m_tempPoints.resize(chart->faces.size() * 3);
  5203. for (uint32_t i = 0; i < faceCount; i++) {
  5204. const uint32_t f = chart->faces[i];
  5205. for (uint32_t j = 0; j < 3; j++)
  5206. m_tempPoints[i * 3 + j] = m_data.mesh->position(m_data.mesh->vertexAt(f * 3 + j));
  5207. }
  5208. return Fit::computeBasis(m_tempPoints, basis);
  5209. }
  5210. bool isFaceFlipped(uint32_t face) const
  5211. {
  5212. const Vector2 &v1 = m_texcoords[face * 3 + 0];
  5213. const Vector2 &v2 = m_texcoords[face * 3 + 1];
  5214. const Vector2 &v3 = m_texcoords[face * 3 + 2];
  5215. const float parametricArea = ((v2.x - v1.x) * (v3.y - v1.y) - (v3.x - v1.x) * (v2.y - v1.y)) * 0.5f;
  5216. return parametricArea < 0.0f;
  5217. }
  5218. void parameterizeChart(const Chart *chart)
  5219. {
  5220. const uint32_t faceCount = chart->faces.size();
  5221. for (uint32_t i = 0; i < faceCount; i++) {
  5222. const uint32_t face = chart->faces[i];
  5223. for (uint32_t j = 0; j < 3; j++) {
  5224. const uint32_t offset = face * 3 + j;
  5225. const Vector3 &pos = m_data.mesh->position(m_data.mesh->vertexAt(offset));
  5226. m_texcoords[offset] = Vector2(dot(chart->basis.tangent, pos), dot(chart->basis.bitangent, pos));
  5227. }
  5228. }
  5229. }
  5230. // m_faceCharts for the chart faces must be set to the chart ID. Needed to compute boundary edges.
  5231. bool isChartParameterizationValid(const Chart *chart)
  5232. {
  5233. const uint32_t faceCount = chart->faces.size();
  5234. // Check for flipped faces in the parameterization. OK if all are flipped.
  5235. uint32_t flippedFaceCount = 0;
  5236. for (uint32_t i = 0; i < faceCount; i++) {
  5237. if (isFaceFlipped(chart->faces[i]))
  5238. flippedFaceCount++;
  5239. }
  5240. if (flippedFaceCount != 0 && flippedFaceCount != faceCount)
  5241. return false;
  5242. // Check for boundary intersection in the parameterization.
  5243. XA_PROFILE_START(clusteredChartsPlaceSeedsBoundaryIntersection)
  5244. XA_PROFILE_START(clusteredChartsGrowBoundaryIntersection)
  5245. m_boundaryGrid.reset(m_texcoords);
  5246. for (uint32_t i = 0; i < faceCount; i++) {
  5247. const uint32_t f = chart->faces[i];
  5248. for (uint32_t j = 0; j < 3; j++) {
  5249. const uint32_t edge = f * 3 + j;
  5250. if (isChartBoundaryEdge(chart, edge))
  5251. m_boundaryGrid.append(edge);
  5252. }
  5253. }
  5254. const bool intersection = m_boundaryGrid.intersect(m_data.mesh->epsilon());
  5255. #if XA_PROFILE
  5256. if (m_placingSeeds)
  5257. XA_PROFILE_END(clusteredChartsPlaceSeedsBoundaryIntersection)
  5258. else
  5259. XA_PROFILE_END(clusteredChartsGrowBoundaryIntersection)
  5260. #endif
  5261. if (intersection)
  5262. return false;
  5263. return true;
  5264. }
  5265. bool addFaceToChart(Chart *chart, uint32_t face)
  5266. {
  5267. XA_DEBUG_ASSERT(!m_data.isFaceInChart.get(face));
  5268. const uint32_t oldFaceCount = chart->faces.size();
  5269. const bool firstFace = oldFaceCount == 0;
  5270. // Append the face and any coplanar connected faces to the chart faces array.
  5271. chart->faces.push_back(face);
  5272. uint32_t coplanarFace = m_planarCharts.nextRegionFace(face);
  5273. while (coplanarFace != face) {
  5274. XA_DEBUG_ASSERT(!m_data.isFaceInChart.get(coplanarFace));
  5275. chart->faces.push_back(coplanarFace);
  5276. coplanarFace = m_planarCharts.nextRegionFace(coplanarFace);
  5277. }
  5278. const uint32_t faceCount = chart->faces.size();
  5279. // Compute basis.
  5280. Basis basis;
  5281. if (firstFace) {
  5282. // Use the first face normal.
  5283. // Use any edge as the tangent vector.
  5284. basis.normal = m_data.faceNormals[face];
  5285. basis.tangent = normalize(m_data.mesh->position(m_data.mesh->vertexAt(face * 3 + 0)) - m_data.mesh->position(m_data.mesh->vertexAt(face * 3 + 1)));
  5286. basis.bitangent = cross(basis.normal, basis.tangent);
  5287. } else {
  5288. // Use best fit normal.
  5289. if (!computeChartBasis(chart, &basis)) {
  5290. chart->faces.resize(oldFaceCount);
  5291. return false;
  5292. }
  5293. if (dot(basis.normal, m_data.faceNormals[face]) < 0.0f) // Flip normal if oriented in the wrong direction.
  5294. basis.normal = -basis.normal;
  5295. }
  5296. if (!firstFace) {
  5297. // Compute orthogonal parameterization and check that it is valid.
  5298. parameterizeChart(chart);
  5299. for (uint32_t i = oldFaceCount; i < faceCount; i++)
  5300. m_faceCharts[chart->faces[i]] = chart->id;
  5301. if (!isChartParameterizationValid(chart)) {
  5302. for (uint32_t i = oldFaceCount; i < faceCount; i++)
  5303. m_faceCharts[chart->faces[i]] = -1;
  5304. chart->faces.resize(oldFaceCount);
  5305. return false;
  5306. }
  5307. }
  5308. // Add face(s) to chart.
  5309. chart->basis = basis;
  5310. chart->area = computeArea(chart, face);
  5311. chart->boundaryLength = computeBoundaryLength(chart, face);
  5312. for (uint32_t i = oldFaceCount; i < faceCount; i++) {
  5313. const uint32_t f = chart->faces[i];
  5314. m_faceCharts[f] = chart->id;
  5315. m_facesLeft--;
  5316. m_data.isFaceInChart.set(f);
  5317. chart->centroidSum += m_data.mesh->computeFaceCenter(f);
  5318. }
  5319. chart->centroid = chart->centroidSum / float(chart->faces.size());
  5320. // Refresh candidates.
  5321. chart->candidates.clear();
  5322. for (uint32_t i = 0; i < faceCount; i++) {
  5323. // Traverse neighboring faces, add the ones that do not belong to any chart yet.
  5324. const uint32_t f = chart->faces[i];
  5325. for (uint32_t j = 0; j < 3; j++) {
  5326. const uint32_t edge = f * 3 + j;
  5327. const uint32_t oedge = m_data.mesh->oppositeEdge(edge);
  5328. if (oedge == UINT32_MAX)
  5329. continue; // Boundary edge.
  5330. const uint32_t oface = meshEdgeFace(oedge);
  5331. if (m_data.isFaceInChart.get(oface))
  5332. continue; // Face belongs to another chart.
  5333. if (chart->failedPlanarRegions.contains(m_planarCharts.regionIdFromFace(oface)))
  5334. continue; // Failed to add this faces planar region to the chart before.
  5335. const float cost = computeCost(chart, oface);
  5336. if (cost < FLT_MAX)
  5337. chart->candidates.push(cost, oface);
  5338. }
  5339. }
  5340. return true;
  5341. }
  5342. // Returns true if the seed has changed.
  5343. bool relocateSeed(Chart *chart)
  5344. {
  5345. // Find the first N triangles that fit the proxy best.
  5346. const uint32_t faceCount = chart->faces.size();
  5347. m_bestTriangles.clear();
  5348. for (uint32_t i = 0; i < faceCount; i++) {
  5349. const float cost = computeNormalDeviationMetric(chart, chart->faces[i]);
  5350. m_bestTriangles.push(cost, chart->faces[i]);
  5351. }
  5352. // Of those, choose the most central triangle.
  5353. uint32_t mostCentral = 0;
  5354. float minDistance = FLT_MAX;
  5355. for (;;) {
  5356. if (m_bestTriangles.count() == 0)
  5357. break;
  5358. const uint32_t face = m_bestTriangles.pop();
  5359. Vector3 faceCentroid = m_data.mesh->computeFaceCenter(face);
  5360. const float distance = length(chart->centroid - faceCentroid);
  5361. if (distance < minDistance) {
  5362. minDistance = distance;
  5363. mostCentral = face;
  5364. }
  5365. }
  5366. XA_DEBUG_ASSERT(minDistance < FLT_MAX);
  5367. if (mostCentral == chart->seed)
  5368. return false;
  5369. chart->seed = mostCentral;
  5370. return true;
  5371. }
  5372. // Cost is combined metrics * weights.
  5373. float computeCost(Chart *chart, uint32_t face) const
  5374. {
  5375. // Estimate boundary length and area:
  5376. const float newChartArea = computeArea(chart, face);
  5377. const float newBoundaryLength = computeBoundaryLength(chart, face);
  5378. // Enforce limits strictly:
  5379. if (m_data.options.maxChartArea > 0.0f && newChartArea > m_data.options.maxChartArea)
  5380. return FLT_MAX;
  5381. if (m_data.options.maxBoundaryLength > 0.0f && newBoundaryLength > m_data.options.maxBoundaryLength)
  5382. return FLT_MAX;
  5383. // Compute metrics.
  5384. float cost = 0.0f;
  5385. const float normalDeviation = computeNormalDeviationMetric(chart, face);
  5386. if (normalDeviation >= 0.707f) // ~75 degrees
  5387. return FLT_MAX;
  5388. cost += m_data.options.normalDeviationWeight * normalDeviation;
  5389. // Penalize faces that cross seams, reward faces that close seams or reach boundaries.
  5390. // Make sure normal seams are fully respected:
  5391. const float normalSeam = computeNormalSeamMetric(chart, face);
  5392. if (m_data.options.normalSeamWeight >= 1000.0f && normalSeam > 0.0f)
  5393. return FLT_MAX;
  5394. cost += m_data.options.normalSeamWeight * normalSeam;
  5395. cost += m_data.options.roundnessWeight * computeRoundnessMetric(chart, newBoundaryLength, newChartArea);
  5396. cost += m_data.options.straightnessWeight * computeStraightnessMetric(chart, face);
  5397. cost += m_data.options.textureSeamWeight * computeTextureSeamMetric(chart, face);
  5398. //float R = evaluateCompletenessMetric(chart, face);
  5399. //float D = evaluateDihedralAngleMetric(chart, face);
  5400. // @@ Add a metric based on local dihedral angle.
  5401. // @@ Tweaking the normal and texture seam metrics.
  5402. // - Cause more impedance. Never cross 90 degree edges.
  5403. XA_DEBUG_ASSERT(isFinite(cost));
  5404. return cost;
  5405. }
  5406. // Returns a value in [0-1].
  5407. // 0 if face normal is coplanar to the chart's best fit normal.
  5408. // 1 if face normal is perpendicular.
  5409. float computeNormalDeviationMetric(Chart *chart, uint32_t face) const
  5410. {
  5411. // All faces in coplanar regions have the same normal, can use any face.
  5412. const Vector3 faceNormal = m_data.faceNormals[face];
  5413. // Use plane fitting metric for now:
  5414. return min(1.0f - dot(faceNormal, chart->basis.normal), 1.0f); // @@ normal deviations should be weighted by face area
  5415. }
  5416. float computeRoundnessMetric(Chart *chart, float newBoundaryLength, float newChartArea) const
  5417. {
  5418. const float oldRoundness = square(chart->boundaryLength) / chart->area;
  5419. const float newRoundness = square(newBoundaryLength) / newChartArea;
  5420. return 1.0f - oldRoundness / newRoundness;
  5421. }
  5422. float computeStraightnessMetric(Chart *chart, uint32_t firstFace) const
  5423. {
  5424. float l_out = 0.0f; // Length of firstFace planar region boundary that doesn't border the chart.
  5425. float l_in = 0.0f; // Length that does border the chart.
  5426. const uint32_t planarRegionId = m_planarCharts.regionIdFromFace(firstFace);
  5427. uint32_t face = firstFace;
  5428. for (;;) {
  5429. for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
  5430. const float l = m_data.edgeLengths[it.edge()];
  5431. if (it.isBoundary()) {
  5432. l_out += l;
  5433. } else if (m_planarCharts.regionIdFromFace(it.oppositeFace()) != planarRegionId) {
  5434. if (m_faceCharts[it.oppositeFace()] != chart->id)
  5435. l_out += l;
  5436. else
  5437. l_in += l;
  5438. }
  5439. }
  5440. face = m_planarCharts.nextRegionFace(face);
  5441. if (face == firstFace)
  5442. break;
  5443. }
  5444. #if 1
  5445. float ratio = (l_out - l_in) / (l_out + l_in);
  5446. return min(ratio, 0.0f); // Only use the straightness metric to close gaps.
  5447. #else
  5448. return 1.0f - l_in / l_out;
  5449. #endif
  5450. }
  5451. bool isNormalSeam(uint32_t edge) const
  5452. {
  5453. const uint32_t oppositeEdge = m_data.mesh->oppositeEdge(edge);
  5454. if (oppositeEdge == UINT32_MAX)
  5455. return false; // boundary edge
  5456. if (m_data.mesh->flags() & MeshFlags::HasNormals) {
  5457. const uint32_t v0 = m_data.mesh->vertexAt(meshEdgeIndex0(edge));
  5458. const uint32_t v1 = m_data.mesh->vertexAt(meshEdgeIndex1(edge));
  5459. const uint32_t ov0 = m_data.mesh->vertexAt(meshEdgeIndex0(oppositeEdge));
  5460. const uint32_t ov1 = m_data.mesh->vertexAt(meshEdgeIndex1(oppositeEdge));
  5461. if (v0 == ov1 && v1 == ov0)
  5462. return false;
  5463. return !equal(m_data.mesh->normal(v0), m_data.mesh->normal(ov1), kNormalEpsilon) || !equal(m_data.mesh->normal(v1), m_data.mesh->normal(ov0), kNormalEpsilon);
  5464. }
  5465. const uint32_t f0 = meshEdgeFace(edge);
  5466. const uint32_t f1 = meshEdgeFace(oppositeEdge);
  5467. if (m_planarCharts.regionIdFromFace(f0) == m_planarCharts.regionIdFromFace(f1))
  5468. return false;
  5469. return !equal(m_data.faceNormals[f0], m_data.faceNormals[f1], kNormalEpsilon);
  5470. }
  5471. float computeNormalSeamMetric(Chart *chart, uint32_t firstFace) const
  5472. {
  5473. float seamFactor = 0.0f, totalLength = 0.0f;
  5474. uint32_t face = firstFace;
  5475. for (;;) {
  5476. for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
  5477. if (it.isBoundary())
  5478. continue;
  5479. if (m_faceCharts[it.oppositeFace()] != chart->id)
  5480. continue;
  5481. float l = m_data.edgeLengths[it.edge()];
  5482. totalLength += l;
  5483. if (!it.isSeam())
  5484. continue;
  5485. // Make sure it's a normal seam.
  5486. if (isNormalSeam(it.edge())) {
  5487. float d;
  5488. if (m_data.mesh->flags() & MeshFlags::HasNormals) {
  5489. const Vector3 &n0 = m_data.mesh->normal(it.vertex0());
  5490. const Vector3 &n1 = m_data.mesh->normal(it.vertex1());
  5491. const Vector3 &on0 = m_data.mesh->normal(m_data.mesh->vertexAt(meshEdgeIndex0(it.oppositeEdge())));
  5492. const Vector3 &on1 = m_data.mesh->normal(m_data.mesh->vertexAt(meshEdgeIndex1(it.oppositeEdge())));
  5493. const float d0 = clamp(dot(n0, on1), 0.0f, 1.0f);
  5494. const float d1 = clamp(dot(n1, on0), 0.0f, 1.0f);
  5495. d = (d0 + d1) * 0.5f;
  5496. } else {
  5497. d = clamp(dot(m_data.faceNormals[face], m_data.faceNormals[meshEdgeFace(it.oppositeEdge())]), 0.0f, 1.0f);
  5498. }
  5499. l *= 1 - d;
  5500. seamFactor += l;
  5501. }
  5502. }
  5503. face = m_planarCharts.nextRegionFace(face);
  5504. if (face == firstFace)
  5505. break;
  5506. }
  5507. if (seamFactor <= 0.0f)
  5508. return 0.0f;
  5509. return seamFactor / totalLength;
  5510. }
  5511. float computeTextureSeamMetric(Chart *chart, uint32_t firstFace) const
  5512. {
  5513. float seamLength = 0.0f, totalLength = 0.0f;
  5514. uint32_t face = firstFace;
  5515. for (;;) {
  5516. for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
  5517. if (it.isBoundary())
  5518. continue;
  5519. if (m_faceCharts[it.oppositeFace()] != chart->id)
  5520. continue;
  5521. float l = m_data.edgeLengths[it.edge()];
  5522. totalLength += l;
  5523. if (!it.isSeam())
  5524. continue;
  5525. // Make sure it's a texture seam.
  5526. if (it.isTextureSeam())
  5527. seamLength += l;
  5528. }
  5529. face = m_planarCharts.nextRegionFace(face);
  5530. if (face == firstFace)
  5531. break;
  5532. }
  5533. if (seamLength <= 0.0f)
  5534. return 0.0f; // Avoid division by zero.
  5535. return seamLength / totalLength;
  5536. }
  5537. float computeArea(Chart *chart, uint32_t firstFace) const
  5538. {
  5539. float area = chart->area;
  5540. uint32_t face = firstFace;
  5541. for (;;) {
  5542. area += m_data.faceAreas[face];
  5543. face = m_planarCharts.nextRegionFace(face);
  5544. if (face == firstFace)
  5545. break;
  5546. }
  5547. return area;
  5548. }
  5549. float computeBoundaryLength(Chart *chart, uint32_t firstFace) const
  5550. {
  5551. float boundaryLength = chart->boundaryLength;
  5552. // Add new edges, subtract edges shared with the chart.
  5553. const uint32_t planarRegionId = m_planarCharts.regionIdFromFace(firstFace);
  5554. uint32_t face = firstFace;
  5555. for (;;) {
  5556. for (Mesh::FaceEdgeIterator it(m_data.mesh, face); !it.isDone(); it.advance()) {
  5557. const float edgeLength = m_data.edgeLengths[it.edge()];
  5558. if (it.isBoundary()) {
  5559. boundaryLength += edgeLength;
  5560. } else if (m_planarCharts.regionIdFromFace(it.oppositeFace()) != planarRegionId) {
  5561. if (m_faceCharts[it.oppositeFace()] != chart->id)
  5562. boundaryLength += edgeLength;
  5563. else
  5564. boundaryLength -= edgeLength;
  5565. }
  5566. }
  5567. face = m_planarCharts.nextRegionFace(face);
  5568. if (face == firstFace)
  5569. break;
  5570. }
  5571. return max(0.0f, boundaryLength); // @@ Hack!
  5572. }
  5573. bool mergeChart(Chart *owner, Chart *chart, float sharedBoundaryLength)
  5574. {
  5575. const uint32_t oldOwnerFaceCount = owner->faces.size();
  5576. const uint32_t chartFaceCount = chart->faces.size();
  5577. owner->faces.push_back(chart->faces);
  5578. for (uint32_t i = 0; i < chartFaceCount; i++) {
  5579. XA_DEBUG_ASSERT(m_faceCharts[chart->faces[i]] == chart->id);
  5580. m_faceCharts[chart->faces[i]] = owner->id;
  5581. }
  5582. // Compute basis using best fit normal.
  5583. Basis basis;
  5584. if (!computeChartBasis(owner, &basis)) {
  5585. owner->faces.resize(oldOwnerFaceCount);
  5586. for (uint32_t i = 0; i < chartFaceCount; i++)
  5587. m_faceCharts[chart->faces[i]] = chart->id;
  5588. return false;
  5589. }
  5590. if (dot(basis.normal, m_data.faceNormals[owner->faces[0]]) < 0.0f) // Flip normal if oriented in the wrong direction.
  5591. basis.normal = -basis.normal;
  5592. // Compute orthogonal parameterization and check that it is valid.
  5593. parameterizeChart(owner);
  5594. if (!isChartParameterizationValid(owner)) {
  5595. owner->faces.resize(oldOwnerFaceCount);
  5596. for (uint32_t i = 0; i < chartFaceCount; i++)
  5597. m_faceCharts[chart->faces[i]] = chart->id;
  5598. return false;
  5599. }
  5600. // Merge chart.
  5601. owner->basis = basis;
  5602. owner->failedPlanarRegions.push_back(chart->failedPlanarRegions);
  5603. // Update adjacencies?
  5604. owner->area += chart->area;
  5605. owner->boundaryLength += chart->boundaryLength - sharedBoundaryLength;
  5606. // Delete chart.
  5607. m_charts[chart->id] = nullptr;
  5608. chart->~Chart();
  5609. XA_FREE(chart);
  5610. return true;
  5611. }
  5612. private:
  5613. AtlasData &m_data;
  5614. const PlanarCharts &m_planarCharts;
  5615. Array<Vector2> m_texcoords;
  5616. uint32_t m_facesLeft;
  5617. Array<int> m_faceCharts;
  5618. Array<Chart *> m_charts;
  5619. CostQueue m_bestTriangles;
  5620. Array<Vector3> m_tempPoints;
  5621. UniformGrid2 m_boundaryGrid;
  5622. #if XA_MERGE_CHARTS
  5623. // mergeCharts
  5624. Array<float> m_sharedBoundaryLengths;
  5625. Array<float> m_sharedBoundaryLengthsNoSeams;
  5626. Array<uint32_t> m_sharedBoundaryEdgeCountNoSeams;
  5627. #endif
  5628. bool m_placingSeeds;
  5629. };
  5630. struct ChartGeneratorType
  5631. {
  5632. enum Enum
  5633. {
  5634. OriginalUv,
  5635. Planar,
  5636. Clustered,
  5637. Piecewise
  5638. };
  5639. };
  5640. struct Atlas
  5641. {
  5642. Atlas() : m_originalUvCharts(m_data), m_planarCharts(m_data), m_clusteredCharts(m_data, m_planarCharts) {}
  5643. uint32_t chartCount() const
  5644. {
  5645. return m_originalUvCharts.chartCount() + m_planarCharts.chartCount() + m_clusteredCharts.chartCount();
  5646. }
  5647. ConstArrayView<uint32_t> chartFaces(uint32_t chartIndex) const
  5648. {
  5649. if (chartIndex < m_originalUvCharts.chartCount())
  5650. return m_originalUvCharts.chartFaces(chartIndex);
  5651. chartIndex -= m_originalUvCharts.chartCount();
  5652. if (chartIndex < m_planarCharts.chartCount())
  5653. return m_planarCharts.chartFaces(chartIndex);
  5654. chartIndex -= m_planarCharts.chartCount();
  5655. return m_clusteredCharts.chartFaces(chartIndex);
  5656. }
  5657. const Basis &chartBasis(uint32_t chartIndex) const
  5658. {
  5659. if (chartIndex < m_originalUvCharts.chartCount())
  5660. return m_originalUvCharts.chartBasis(chartIndex);
  5661. chartIndex -= m_originalUvCharts.chartCount();
  5662. if (chartIndex < m_planarCharts.chartCount())
  5663. return m_planarCharts.chartBasis(chartIndex);
  5664. chartIndex -= m_planarCharts.chartCount();
  5665. return m_clusteredCharts.chartBasis(chartIndex);
  5666. }
  5667. ChartGeneratorType::Enum chartGeneratorType(uint32_t chartIndex) const
  5668. {
  5669. if (chartIndex < m_originalUvCharts.chartCount())
  5670. return ChartGeneratorType::OriginalUv;
  5671. chartIndex -= m_originalUvCharts.chartCount();
  5672. if (chartIndex < m_planarCharts.chartCount())
  5673. return ChartGeneratorType::Planar;
  5674. return ChartGeneratorType::Clustered;
  5675. }
  5676. void reset(const Mesh *mesh, const ChartOptions &options)
  5677. {
  5678. XA_PROFILE_START(buildAtlasInit)
  5679. m_data.options = options;
  5680. m_data.mesh = mesh;
  5681. m_data.compute();
  5682. XA_PROFILE_END(buildAtlasInit)
  5683. }
  5684. void compute()
  5685. {
  5686. if (m_data.options.useInputMeshUvs) {
  5687. XA_PROFILE_START(originalUvCharts)
  5688. m_originalUvCharts.compute();
  5689. XA_PROFILE_END(originalUvCharts)
  5690. }
  5691. XA_PROFILE_START(planarCharts)
  5692. m_planarCharts.compute();
  5693. XA_PROFILE_END(planarCharts)
  5694. XA_PROFILE_START(clusteredCharts)
  5695. m_clusteredCharts.compute();
  5696. XA_PROFILE_END(clusteredCharts)
  5697. }
  5698. private:
  5699. AtlasData m_data;
  5700. OriginalUvCharts m_originalUvCharts;
  5701. PlanarCharts m_planarCharts;
  5702. ClusteredCharts m_clusteredCharts;
  5703. };
  5704. struct ComputeUvMeshChartsTaskArgs
  5705. {
  5706. UvMesh *mesh;
  5707. Progress *progress;
  5708. };
  5709. // Charts are found by floodfilling faces without crossing UV seams.
  5710. struct ComputeUvMeshChartsTask
  5711. {
  5712. ComputeUvMeshChartsTask(ComputeUvMeshChartsTaskArgs *args) : m_mesh(args->mesh), m_progress(args->progress), m_uvToEdgeMap(MemTag::Default, m_mesh->indices.size()), m_faceAssigned(m_mesh->indices.size() / 3) {}
  5713. void run()
  5714. {
  5715. const uint32_t vertexCount = m_mesh->texcoords.size();
  5716. const uint32_t indexCount = m_mesh->indices.size();
  5717. const uint32_t faceCount = indexCount / 3;
  5718. // A vertex can only be assigned to one chart.
  5719. m_mesh->vertexToChartMap.resize(vertexCount);
  5720. m_mesh->vertexToChartMap.fill(UINT32_MAX);
  5721. // Map vertex UV to edge. Face is then edge / 3.
  5722. for (uint32_t i = 0; i < indexCount; i++)
  5723. m_uvToEdgeMap.add(m_mesh->texcoords[m_mesh->indices[i]]);
  5724. // Find charts.
  5725. m_faceAssigned.zeroOutMemory();
  5726. for (uint32_t f = 0; f < faceCount; f++) {
  5727. if (m_progress->cancel)
  5728. return;
  5729. m_progress->increment(1);
  5730. // Found an unassigned face, see if it can be added.
  5731. const uint32_t chartIndex = m_mesh->charts.size();
  5732. if (!canAddFaceToChart(chartIndex, f))
  5733. continue;
  5734. // Face is OK, create a new chart with the face.
  5735. UvMeshChart *chart = XA_NEW(MemTag::Default, UvMeshChart);
  5736. m_mesh->charts.push_back(chart);
  5737. chart->material = m_mesh->faceMaterials.isEmpty() ? 0 : m_mesh->faceMaterials[f];
  5738. addFaceToChart(chartIndex, f);
  5739. // Walk incident faces and assign them to the chart.
  5740. uint32_t f2 = 0;
  5741. for (;;) {
  5742. bool newFaceAssigned = false;
  5743. const uint32_t faceCount2 = chart->faces.size();
  5744. for (; f2 < faceCount2; f2++) {
  5745. const uint32_t face = chart->faces[f2];
  5746. for (uint32_t i = 0; i < 3; i++) {
  5747. // Add any valid faces with colocal UVs to the chart.
  5748. const Vector2 &uv = m_mesh->texcoords[m_mesh->indices[face * 3 + i]];
  5749. uint32_t edge = m_uvToEdgeMap.get(uv);
  5750. while (edge != UINT32_MAX) {
  5751. const uint32_t newFace = edge / 3;
  5752. if (canAddFaceToChart(chartIndex, newFace)) {
  5753. addFaceToChart(chartIndex, newFace);
  5754. newFaceAssigned = true;
  5755. }
  5756. edge = m_uvToEdgeMap.getNext(uv, edge);
  5757. }
  5758. }
  5759. }
  5760. if (!newFaceAssigned)
  5761. break;
  5762. }
  5763. }
  5764. }
  5765. private:
  5766. // The chart at chartIndex doesn't have to exist yet.
  5767. bool canAddFaceToChart(uint32_t chartIndex, uint32_t face) const
  5768. {
  5769. if (m_faceAssigned.get(face))
  5770. return false; // Already assigned to a chart.
  5771. if (m_mesh->faceIgnore.get(face))
  5772. return false; // Face is ignored (zero area or nan UVs).
  5773. if (!m_mesh->faceMaterials.isEmpty() && chartIndex < m_mesh->charts.size()) {
  5774. if (m_mesh->faceMaterials[face] != m_mesh->charts[chartIndex]->material)
  5775. return false; // Materials don't match.
  5776. }
  5777. for (uint32_t i = 0; i < 3; i++) {
  5778. const uint32_t vertex = m_mesh->indices[face * 3 + i];
  5779. if (m_mesh->vertexToChartMap[vertex] != UINT32_MAX && m_mesh->vertexToChartMap[vertex] != chartIndex)
  5780. return false; // Vertex already assigned to another chart.
  5781. }
  5782. return true;
  5783. }
  5784. void addFaceToChart(uint32_t chartIndex, uint32_t face)
  5785. {
  5786. UvMeshChart *chart = m_mesh->charts[chartIndex];
  5787. m_faceAssigned.set(face);
  5788. chart->faces.push_back(face);
  5789. for (uint32_t i = 0; i < 3; i++) {
  5790. const uint32_t vertex = m_mesh->indices[face * 3 + i];
  5791. m_mesh->vertexToChartMap[vertex] = chartIndex;
  5792. chart->indices.push_back(vertex);
  5793. }
  5794. }
  5795. UvMesh * const m_mesh;
  5796. Progress * const m_progress;
  5797. HashMap<Vector2> m_uvToEdgeMap; // Face is edge / 3.
  5798. BitArray m_faceAssigned;
  5799. };
  5800. static void runComputeUvMeshChartsTask(void * /*groupUserData*/, void *taskUserData)
  5801. {
  5802. XA_PROFILE_START(computeChartsThread)
  5803. ComputeUvMeshChartsTask task((ComputeUvMeshChartsTaskArgs *)taskUserData);
  5804. task.run();
  5805. XA_PROFILE_END(computeChartsThread)
  5806. }
  5807. static bool computeUvMeshCharts(TaskScheduler *taskScheduler, ArrayView<UvMesh *> meshes, ProgressFunc progressFunc, void *progressUserData)
  5808. {
  5809. uint32_t totalFaceCount = 0;
  5810. for (uint32_t i = 0; i < meshes.length; i++)
  5811. totalFaceCount += meshes[i]->indices.size() / 3;
  5812. Progress progress(ProgressCategory::ComputeCharts, progressFunc, progressUserData, totalFaceCount);
  5813. TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(nullptr, meshes.length);
  5814. Array<ComputeUvMeshChartsTaskArgs> taskArgs;
  5815. taskArgs.resize(meshes.length);
  5816. for (uint32_t i = 0; i < meshes.length; i++)
  5817. {
  5818. ComputeUvMeshChartsTaskArgs &args = taskArgs[i];
  5819. args.mesh = meshes[i];
  5820. args.progress = &progress;
  5821. Task task;
  5822. task.userData = &args;
  5823. task.func = runComputeUvMeshChartsTask;
  5824. taskScheduler->run(taskGroup, task);
  5825. }
  5826. taskScheduler->wait(&taskGroup);
  5827. return !progress.cancel;
  5828. }
  5829. } // namespace segment
  5830. namespace param {
  5831. // Fast sweep in 3 directions
  5832. static bool findApproximateDiameterVertices(Mesh *mesh, uint32_t *a, uint32_t *b)
  5833. {
  5834. XA_DEBUG_ASSERT(a != nullptr);
  5835. XA_DEBUG_ASSERT(b != nullptr);
  5836. const uint32_t vertexCount = mesh->vertexCount();
  5837. uint32_t minVertex[3];
  5838. uint32_t maxVertex[3];
  5839. minVertex[0] = minVertex[1] = minVertex[2] = UINT32_MAX;
  5840. maxVertex[0] = maxVertex[1] = maxVertex[2] = UINT32_MAX;
  5841. for (uint32_t v = 1; v < vertexCount; v++) {
  5842. if (mesh->isBoundaryVertex(v)) {
  5843. minVertex[0] = minVertex[1] = minVertex[2] = v;
  5844. maxVertex[0] = maxVertex[1] = maxVertex[2] = v;
  5845. break;
  5846. }
  5847. }
  5848. if (minVertex[0] == UINT32_MAX) {
  5849. // Input mesh has not boundaries.
  5850. return false;
  5851. }
  5852. for (uint32_t v = 1; v < vertexCount; v++) {
  5853. if (!mesh->isBoundaryVertex(v)) {
  5854. // Skip interior vertices.
  5855. continue;
  5856. }
  5857. const Vector3 &pos = mesh->position(v);
  5858. if (pos.x < mesh->position(minVertex[0]).x)
  5859. minVertex[0] = v;
  5860. else if (pos.x > mesh->position(maxVertex[0]).x)
  5861. maxVertex[0] = v;
  5862. if (pos.y < mesh->position(minVertex[1]).y)
  5863. minVertex[1] = v;
  5864. else if (pos.y > mesh->position(maxVertex[1]).y)
  5865. maxVertex[1] = v;
  5866. if (pos.z < mesh->position(minVertex[2]).z)
  5867. minVertex[2] = v;
  5868. else if (pos.z > mesh->position(maxVertex[2]).z)
  5869. maxVertex[2] = v;
  5870. }
  5871. float lengths[3];
  5872. for (int i = 0; i < 3; i++) {
  5873. lengths[i] = length(mesh->position(minVertex[i]) - mesh->position(maxVertex[i]));
  5874. }
  5875. if (lengths[0] > lengths[1] && lengths[0] > lengths[2]) {
  5876. *a = minVertex[0];
  5877. *b = maxVertex[0];
  5878. } else if (lengths[1] > lengths[2]) {
  5879. *a = minVertex[1];
  5880. *b = maxVertex[1];
  5881. } else {
  5882. *a = minVertex[2];
  5883. *b = maxVertex[2];
  5884. }
  5885. return true;
  5886. }
  5887. // From OpenNL LSCM example.
  5888. // Computes the coordinates of the vertices of a triangle in a local 2D orthonormal basis of the triangle's plane.
  5889. static void projectTriangle(Vector3 p0, Vector3 p1, Vector3 p2, Vector2 *z0, Vector2 *z1, Vector2 *z2)
  5890. {
  5891. Vector3 X = normalize(p1 - p0);
  5892. Vector3 Z = normalize(cross(X, p2 - p0));
  5893. Vector3 Y = cross(Z, X);
  5894. Vector3 &O = p0;
  5895. *z0 = Vector2(0, 0);
  5896. *z1 = Vector2(length(p1 - O), 0);
  5897. *z2 = Vector2(dot(p2 - O, X), dot(p2 - O, Y));
  5898. }
  5899. // Conformal relations from Brecht Van Lommel (based on ABF):
  5900. static float vec_angle_cos(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3)
  5901. {
  5902. Vector3 d1 = v1 - v2;
  5903. Vector3 d2 = v3 - v2;
  5904. return clamp(dot(d1, d2) / (length(d1) * length(d2)), -1.0f, 1.0f);
  5905. }
  5906. static float vec_angle(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3)
  5907. {
  5908. float dot = vec_angle_cos(v1, v2, v3);
  5909. return acosf(dot);
  5910. }
  5911. static void triangle_angles(const Vector3 &v1, const Vector3 &v2, const Vector3 &v3, float *a1, float *a2, float *a3)
  5912. {
  5913. *a1 = vec_angle(v3, v1, v2);
  5914. *a2 = vec_angle(v1, v2, v3);
  5915. *a3 = kPi - *a2 - *a1;
  5916. }
  5917. static bool setup_abf_relations(opennl::NLContext *context, int id0, int id1, int id2, const Vector3 &p0, const Vector3 &p1, const Vector3 &p2)
  5918. {
  5919. // @@ IC: Wouldn't it be more accurate to return cos and compute 1-cos^2?
  5920. // It does indeed seem to be a little bit more robust.
  5921. // @@ Need to revisit this more carefully!
  5922. float a0, a1, a2;
  5923. triangle_angles(p0, p1, p2, &a0, &a1, &a2);
  5924. if (a0 == 0.0f || a1 == 0.0f || a2 == 0.0f)
  5925. return false;
  5926. float s0 = sinf(a0);
  5927. float s1 = sinf(a1);
  5928. float s2 = sinf(a2);
  5929. if (s1 > s0 && s1 > s2) {
  5930. swap(s1, s2);
  5931. swap(s0, s1);
  5932. swap(a1, a2);
  5933. swap(a0, a1);
  5934. swap(id1, id2);
  5935. swap(id0, id1);
  5936. } else if (s0 > s1 && s0 > s2) {
  5937. swap(s0, s2);
  5938. swap(s0, s1);
  5939. swap(a0, a2);
  5940. swap(a0, a1);
  5941. swap(id0, id2);
  5942. swap(id0, id1);
  5943. }
  5944. float c0 = cosf(a0);
  5945. float ratio = (s2 == 0.0f) ? 1.0f : s1 / s2;
  5946. float cosine = c0 * ratio;
  5947. float sine = s0 * ratio;
  5948. // Note : 2*id + 0 --> u
  5949. // 2*id + 1 --> v
  5950. int u0_id = 2 * id0 + 0;
  5951. int v0_id = 2 * id0 + 1;
  5952. int u1_id = 2 * id1 + 0;
  5953. int v1_id = 2 * id1 + 1;
  5954. int u2_id = 2 * id2 + 0;
  5955. int v2_id = 2 * id2 + 1;
  5956. // Real part
  5957. opennl::nlBegin(context, NL_ROW);
  5958. opennl::nlCoefficient(context, u0_id, cosine - 1.0f);
  5959. opennl::nlCoefficient(context, v0_id, -sine);
  5960. opennl::nlCoefficient(context, u1_id, -cosine);
  5961. opennl::nlCoefficient(context, v1_id, sine);
  5962. opennl::nlCoefficient(context, u2_id, 1);
  5963. opennl::nlEnd(context, NL_ROW);
  5964. // Imaginary part
  5965. opennl::nlBegin(context, NL_ROW);
  5966. opennl::nlCoefficient(context, u0_id, sine);
  5967. opennl::nlCoefficient(context, v0_id, cosine - 1.0f);
  5968. opennl::nlCoefficient(context, u1_id, -sine);
  5969. opennl::nlCoefficient(context, v1_id, -cosine);
  5970. opennl::nlCoefficient(context, v2_id, 1);
  5971. opennl::nlEnd(context, NL_ROW);
  5972. return true;
  5973. }
  5974. static bool computeLeastSquaresConformalMap(Mesh *mesh)
  5975. {
  5976. uint32_t lockedVertex0, lockedVertex1;
  5977. if (!findApproximateDiameterVertices(mesh, &lockedVertex0, &lockedVertex1)) {
  5978. // Mesh has no boundaries.
  5979. return false;
  5980. }
  5981. const uint32_t vertexCount = mesh->vertexCount();
  5982. opennl::NLContext *context = opennl::nlNewContext();
  5983. opennl::nlSolverParameteri(context, NL_NB_VARIABLES, int(2 * vertexCount));
  5984. opennl::nlSolverParameteri(context, NL_MAX_ITERATIONS, int(5 * vertexCount));
  5985. opennl::nlBegin(context, NL_SYSTEM);
  5986. ArrayView<Vector2> texcoords = mesh->texcoords();
  5987. for (uint32_t i = 0; i < vertexCount; i++) {
  5988. opennl::nlSetVariable(context, 2 * i, texcoords[i].x);
  5989. opennl::nlSetVariable(context, 2 * i + 1, texcoords[i].y);
  5990. if (i == lockedVertex0 || i == lockedVertex1) {
  5991. opennl::nlLockVariable(context, 2 * i);
  5992. opennl::nlLockVariable(context, 2 * i + 1);
  5993. }
  5994. }
  5995. opennl::nlBegin(context, NL_MATRIX);
  5996. const uint32_t faceCount = mesh->faceCount();
  5997. ConstArrayView<Vector3> positions = mesh->positions();
  5998. ConstArrayView<uint32_t> indices = mesh->indices();
  5999. for (uint32_t f = 0; f < faceCount; f++) {
  6000. const uint32_t v0 = indices[f * 3 + 0];
  6001. const uint32_t v1 = indices[f * 3 + 1];
  6002. const uint32_t v2 = indices[f * 3 + 2];
  6003. if (!setup_abf_relations(context, v0, v1, v2, positions[v0], positions[v1], positions[v2])) {
  6004. Vector2 z0, z1, z2;
  6005. projectTriangle(positions[v0], positions[v1], positions[v2], &z0, &z1, &z2);
  6006. double a = z1.x - z0.x;
  6007. double b = z1.y - z0.y;
  6008. double c = z2.x - z0.x;
  6009. double d = z2.y - z0.y;
  6010. XA_DEBUG_ASSERT(b == 0.0);
  6011. // Note : 2*id + 0 --> u
  6012. // 2*id + 1 --> v
  6013. uint32_t u0_id = 2 * v0;
  6014. uint32_t v0_id = 2 * v0 + 1;
  6015. uint32_t u1_id = 2 * v1;
  6016. uint32_t v1_id = 2 * v1 + 1;
  6017. uint32_t u2_id = 2 * v2;
  6018. uint32_t v2_id = 2 * v2 + 1;
  6019. // Note : b = 0
  6020. // Real part
  6021. opennl::nlBegin(context, NL_ROW);
  6022. opennl::nlCoefficient(context, u0_id, -a+c) ;
  6023. opennl::nlCoefficient(context, v0_id, b-d) ;
  6024. opennl::nlCoefficient(context, u1_id, -c) ;
  6025. opennl::nlCoefficient(context, v1_id, d) ;
  6026. opennl::nlCoefficient(context, u2_id, a);
  6027. opennl::nlEnd(context, NL_ROW);
  6028. // Imaginary part
  6029. opennl::nlBegin(context, NL_ROW);
  6030. opennl::nlCoefficient(context, u0_id, -b+d);
  6031. opennl::nlCoefficient(context, v0_id, -a+c);
  6032. opennl::nlCoefficient(context, u1_id, -d);
  6033. opennl::nlCoefficient(context, v1_id, -c);
  6034. opennl::nlCoefficient(context, v2_id, a);
  6035. opennl::nlEnd(context, NL_ROW);
  6036. }
  6037. }
  6038. opennl::nlEnd(context, NL_MATRIX);
  6039. opennl::nlEnd(context, NL_SYSTEM);
  6040. if (!opennl::nlSolve(context)) {
  6041. opennl::nlDeleteContext(context);
  6042. return false;
  6043. }
  6044. for (uint32_t i = 0; i < vertexCount; i++) {
  6045. const double u = opennl::nlGetVariable(context, 2 * i);
  6046. const double v = opennl::nlGetVariable(context, 2 * i + 1);
  6047. texcoords[i] = Vector2((float)u, (float)v);
  6048. XA_DEBUG_ASSERT(!isNan(mesh->texcoord(i).x));
  6049. XA_DEBUG_ASSERT(!isNan(mesh->texcoord(i).y));
  6050. }
  6051. opennl::nlDeleteContext(context);
  6052. return true;
  6053. }
  6054. struct PiecewiseParam
  6055. {
  6056. void reset(const Mesh *mesh)
  6057. {
  6058. m_mesh = mesh;
  6059. const uint32_t faceCount = m_mesh->faceCount();
  6060. const uint32_t vertexCount = m_mesh->vertexCount();
  6061. m_texcoords.resize(vertexCount);
  6062. m_patch.reserve(faceCount);
  6063. m_candidates.reserve(faceCount);
  6064. m_faceInAnyPatch.resize(faceCount);
  6065. m_faceInAnyPatch.zeroOutMemory();
  6066. m_faceInvalid.resize(faceCount);
  6067. m_faceInPatch.resize(faceCount);
  6068. m_vertexInPatch.resize(vertexCount);
  6069. m_faceToCandidate.resize(faceCount);
  6070. }
  6071. ConstArrayView<uint32_t> chartFaces() const { return m_patch; }
  6072. ConstArrayView<Vector2> texcoords() const { return m_texcoords; }
  6073. bool computeChart()
  6074. {
  6075. // Clear per-patch state.
  6076. m_patch.clear();
  6077. m_candidates.clear();
  6078. m_faceToCandidate.zeroOutMemory();
  6079. m_faceInvalid.zeroOutMemory();
  6080. m_faceInPatch.zeroOutMemory();
  6081. m_vertexInPatch.zeroOutMemory();
  6082. // Add the seed face (first unassigned face) to the patch.
  6083. const uint32_t faceCount = m_mesh->faceCount();
  6084. uint32_t seed = UINT32_MAX;
  6085. for (uint32_t f = 0; f < faceCount; f++) {
  6086. if (m_faceInAnyPatch.get(f))
  6087. continue;
  6088. seed = f;
  6089. // Add all 3 vertices.
  6090. Vector2 texcoords[3];
  6091. orthoProjectFace(seed, texcoords);
  6092. for (uint32_t i = 0; i < 3; i++) {
  6093. const uint32_t vertex = m_mesh->vertexAt(seed * 3 + i);
  6094. m_vertexInPatch.set(vertex);
  6095. m_texcoords[vertex] = texcoords[i];
  6096. }
  6097. addFaceToPatch(seed);
  6098. // Initialize the boundary grid.
  6099. m_boundaryGrid.reset(m_texcoords, m_mesh->indices());
  6100. for (Mesh::FaceEdgeIterator it(m_mesh, seed); !it.isDone(); it.advance())
  6101. m_boundaryGrid.append(it.edge());
  6102. break;
  6103. }
  6104. if (seed == UINT32_MAX)
  6105. return false;
  6106. for (;;) {
  6107. // Find the candidate with the lowest cost.
  6108. float lowestCost = FLT_MAX;
  6109. Candidate *bestCandidate = nullptr;
  6110. for (uint32_t i = 0; i < m_candidates.size(); i++) {
  6111. Candidate *candidate = m_candidates[i];
  6112. if (candidate->maxCost < lowestCost) {
  6113. lowestCost = candidate->maxCost;
  6114. bestCandidate = candidate;
  6115. }
  6116. }
  6117. if (!bestCandidate)
  6118. break;
  6119. XA_DEBUG_ASSERT(!bestCandidate->prev); // Must be head of linked candidates.
  6120. // Compute the position by averaging linked candidates (candidates that share the same free vertex).
  6121. Vector2 position(0.0f);
  6122. uint32_t n = 0;
  6123. for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance()) {
  6124. position += it.current()->position;
  6125. n++;
  6126. }
  6127. position *= 1.0f / (float)n;
  6128. const uint32_t freeVertex = bestCandidate->vertex;
  6129. XA_DEBUG_ASSERT(!isNan(position.x));
  6130. XA_DEBUG_ASSERT(!isNan(position.y));
  6131. m_texcoords[freeVertex] = position;
  6132. // Check for flipped faces. This is also done when candidates are first added, but the averaged position of the free vertex is different now, so check again.
  6133. bool invalid = false;
  6134. for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance()) {
  6135. const uint32_t vertex0 = m_mesh->vertexAt(meshEdgeIndex0(it.current()->patchEdge));
  6136. const uint32_t vertex1 = m_mesh->vertexAt(meshEdgeIndex1(it.current()->patchEdge));
  6137. const float freeVertexOrient = orientToEdge(m_texcoords[vertex0], m_texcoords[vertex1], position);
  6138. if ((it.current()->patchVertexOrient < 0.0f && freeVertexOrient < 0.0f) || (it.current()->patchVertexOrient > 0.0f && freeVertexOrient > 0.0f)) {
  6139. invalid = true;
  6140. break;
  6141. }
  6142. }
  6143. // Check for zero area and flipped faces (using area).
  6144. for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance()) {
  6145. const Vector2 a = m_texcoords[m_mesh->vertexAt(it.current()->face * 3 + 0)];
  6146. const Vector2 b = m_texcoords[m_mesh->vertexAt(it.current()->face * 3 + 1)];
  6147. const Vector2 c = m_texcoords[m_mesh->vertexAt(it.current()->face * 3 + 2)];
  6148. const float area = triangleArea(a, b, c);
  6149. if (area <= 0.0f) {
  6150. invalid = true;
  6151. break;
  6152. }
  6153. }
  6154. // Check for boundary intersection.
  6155. if (!invalid) {
  6156. XA_PROFILE_START(parameterizeChartsPiecewiseBoundaryIntersection)
  6157. // Test candidate edges that would form part of the new patch boundary.
  6158. // Ignore boundary edges that would become internal if the candidate faces were added to the patch.
  6159. m_newBoundaryEdges.clear();
  6160. m_ignoreBoundaryEdges.clear();
  6161. for (CandidateIterator candidateIt(bestCandidate); !candidateIt.isDone(); candidateIt.advance()) {
  6162. for (Mesh::FaceEdgeIterator it(m_mesh, candidateIt.current()->face); !it.isDone(); it.advance()) {
  6163. const uint32_t oface = it.oppositeFace();
  6164. if (oface == UINT32_MAX || !m_faceInPatch.get(oface))
  6165. m_newBoundaryEdges.push_back(it.edge());
  6166. if (oface != UINT32_MAX && m_faceInPatch.get(oface))
  6167. m_ignoreBoundaryEdges.push_back(it.oppositeEdge());
  6168. }
  6169. }
  6170. invalid = m_boundaryGrid.intersect(m_mesh->epsilon(), m_newBoundaryEdges, m_ignoreBoundaryEdges);
  6171. XA_PROFILE_END(parameterizeChartsPiecewiseBoundaryIntersection)
  6172. }
  6173. if (invalid) {
  6174. // Mark all faces of linked candidates as invalid.
  6175. for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance())
  6176. m_faceInvalid.set(it.current()->face);
  6177. removeLinkedCandidates(bestCandidate);
  6178. } else {
  6179. // Add vertex to the patch.
  6180. m_vertexInPatch.set(freeVertex);
  6181. // Add faces to the patch.
  6182. for (CandidateIterator it(bestCandidate); !it.isDone(); it.advance())
  6183. addFaceToPatch(it.current()->face);
  6184. // Successfully added candidate face(s) to patch.
  6185. removeLinkedCandidates(bestCandidate);
  6186. // Reset the grid with all edges on the patch boundary.
  6187. XA_PROFILE_START(parameterizeChartsPiecewiseBoundaryIntersection)
  6188. m_boundaryGrid.reset(m_texcoords, m_mesh->indices());
  6189. for (uint32_t i = 0; i < m_patch.size(); i++) {
  6190. for (Mesh::FaceEdgeIterator it(m_mesh, m_patch[i]); !it.isDone(); it.advance()) {
  6191. const uint32_t oface = it.oppositeFace();
  6192. if (oface == UINT32_MAX || !m_faceInPatch.get(oface))
  6193. m_boundaryGrid.append(it.edge());
  6194. }
  6195. }
  6196. XA_PROFILE_END(parameterizeChartsPiecewiseBoundaryIntersection)
  6197. }
  6198. }
  6199. return true;
  6200. }
  6201. private:
  6202. struct Candidate
  6203. {
  6204. uint32_t face, vertex;
  6205. Candidate *prev, *next; // The previous/next candidate with the same vertex.
  6206. Vector2 position;
  6207. float cost;
  6208. float maxCost; // Of all linked candidates.
  6209. uint32_t patchEdge;
  6210. float patchVertexOrient;
  6211. };
  6212. struct CandidateIterator
  6213. {
  6214. CandidateIterator(Candidate *head) : m_current(head) { XA_DEBUG_ASSERT(!head->prev); }
  6215. void advance() { if (m_current != nullptr) { m_current = m_current->next; } }
  6216. bool isDone() const { return !m_current; }
  6217. Candidate *current() { return m_current; }
  6218. private:
  6219. Candidate *m_current;
  6220. };
  6221. const Mesh *m_mesh;
  6222. Array<Vector2> m_texcoords;
  6223. BitArray m_faceInAnyPatch; // Face is in a previous chart patch or the current patch.
  6224. Array<Candidate *> m_candidates; // Incident faces to the patch.
  6225. Array<Candidate *> m_faceToCandidate;
  6226. Array<uint32_t> m_patch; // The current chart patch.
  6227. BitArray m_faceInPatch, m_vertexInPatch; // Face/vertex is in the current patch.
  6228. BitArray m_faceInvalid; // Face cannot be added to the patch - flipped, cost too high or causes boundary intersection.
  6229. UniformGrid2 m_boundaryGrid;
  6230. Array<uint32_t> m_newBoundaryEdges, m_ignoreBoundaryEdges; // Temp arrays used when testing for boundary intersection.
  6231. void addFaceToPatch(uint32_t face)
  6232. {
  6233. XA_DEBUG_ASSERT(!m_faceInPatch.get(face));
  6234. XA_DEBUG_ASSERT(!m_faceInAnyPatch.get(face));
  6235. m_patch.push_back(face);
  6236. m_faceInPatch.set(face);
  6237. m_faceInAnyPatch.set(face);
  6238. // Find new candidate faces on the patch incident to the newly added face.
  6239. for (Mesh::FaceEdgeIterator it(m_mesh, face); !it.isDone(); it.advance()) {
  6240. const uint32_t oface = it.oppositeFace();
  6241. if (oface == UINT32_MAX || m_faceInAnyPatch.get(oface) || m_faceToCandidate[oface])
  6242. continue;
  6243. // Found an active edge on the patch front.
  6244. // Find the free vertex (the vertex that isn't on the active edge).
  6245. // Compute the orientation of the other patch face vertex to the active edge.
  6246. uint32_t freeVertex = UINT32_MAX;
  6247. float orient = 0.0f;
  6248. for (uint32_t j = 0; j < 3; j++) {
  6249. const uint32_t vertex = m_mesh->vertexAt(oface * 3 + j);
  6250. if (vertex != it.vertex0() && vertex != it.vertex1()) {
  6251. freeVertex = vertex;
  6252. orient = orientToEdge(m_texcoords[it.vertex0()], m_texcoords[it.vertex1()], m_texcoords[m_mesh->vertexAt(face * 3 + j)]);
  6253. break;
  6254. }
  6255. }
  6256. XA_DEBUG_ASSERT(freeVertex != UINT32_MAX);
  6257. if (m_vertexInPatch.get(freeVertex)) {
  6258. #if 0
  6259. // If the free vertex is already in the patch, the face is enclosed by the patch. Add the face to the patch - don't need to assign texcoords.
  6260. freeVertex = UINT32_MAX;
  6261. addFaceToPatch(oface);
  6262. #endif
  6263. continue;
  6264. }
  6265. // Check this here rather than above so faces enclosed by the patch are always added.
  6266. if (m_faceInvalid.get(oface))
  6267. continue;
  6268. addCandidateFace(it.edge(), orient, oface, it.oppositeEdge(), freeVertex);
  6269. }
  6270. }
  6271. void addCandidateFace(uint32_t patchEdge, float patchVertexOrient, uint32_t face, uint32_t edge, uint32_t freeVertex)
  6272. {
  6273. XA_DEBUG_ASSERT(!m_faceToCandidate[face]);
  6274. Vector2 texcoords[3];
  6275. orthoProjectFace(face, texcoords);
  6276. // Find corresponding vertices between the patch edge and candidate edge.
  6277. const uint32_t vertex0 = m_mesh->vertexAt(meshEdgeIndex0(patchEdge));
  6278. const uint32_t vertex1 = m_mesh->vertexAt(meshEdgeIndex1(patchEdge));
  6279. uint32_t localVertex0 = UINT32_MAX, localVertex1 = UINT32_MAX, localFreeVertex = UINT32_MAX;
  6280. for (uint32_t i = 0; i < 3; i++) {
  6281. const uint32_t vertex = m_mesh->vertexAt(face * 3 + i);
  6282. if (vertex == m_mesh->vertexAt(meshEdgeIndex1(edge)))
  6283. localVertex0 = i;
  6284. else if (vertex == m_mesh->vertexAt(meshEdgeIndex0(edge)))
  6285. localVertex1 = i;
  6286. else
  6287. localFreeVertex = i;
  6288. }
  6289. // Scale orthogonal projection to match the patch edge.
  6290. const Vector2 patchEdgeVec = m_texcoords[vertex1] - m_texcoords[vertex0];
  6291. const Vector2 localEdgeVec = texcoords[localVertex1] - texcoords[localVertex0];
  6292. const float len1 = length(patchEdgeVec);
  6293. const float len2 = length(localEdgeVec);
  6294. if (len1 <= 0.0f || len2 <= 0.0f)
  6295. return; // Zero length edge.
  6296. const float scale = len1 / len2;
  6297. for (uint32_t i = 0; i < 3; i++)
  6298. texcoords[i] *= scale;
  6299. // Translate to the first vertex on the patch edge.
  6300. const Vector2 translate = m_texcoords[vertex0] - texcoords[localVertex0];
  6301. for (uint32_t i = 0; i < 3; i++)
  6302. texcoords[i] += translate;
  6303. // Compute the angle between the patch edge and the corresponding local edge.
  6304. const float angle = atan2f(patchEdgeVec.y, patchEdgeVec.x) - atan2f(localEdgeVec.y, localEdgeVec.x);
  6305. // Rotate so the patch edge and the corresponding local edge occupy the same space.
  6306. for (uint32_t i = 0; i < 3; i++) {
  6307. if (i == localVertex0)
  6308. continue;
  6309. Vector2 &uv = texcoords[i];
  6310. uv -= texcoords[localVertex0]; // Rotate around the first vertex.
  6311. const float c = cosf(angle);
  6312. const float s = sinf(angle);
  6313. const float x = uv.x * c - uv.y * s;
  6314. const float y = uv.y * c + uv.x * s;
  6315. uv.x = x + texcoords[localVertex0].x;
  6316. uv.y = y + texcoords[localVertex0].y;
  6317. }
  6318. if (isNan(texcoords[localFreeVertex].x) || isNan(texcoords[localFreeVertex].y)) {
  6319. m_faceInvalid.set(face);
  6320. return;
  6321. }
  6322. // Check for local overlap (flipped triangle).
  6323. // The patch face vertex that isn't on the active edge and the free vertex should be oriented on opposite sides to the active edge.
  6324. const float freeVertexOrient = orientToEdge(m_texcoords[vertex0], m_texcoords[vertex1], texcoords[localFreeVertex]);
  6325. if ((patchVertexOrient < 0.0f && freeVertexOrient < 0.0f) || (patchVertexOrient > 0.0f && freeVertexOrient > 0.0f)) {
  6326. m_faceInvalid.set(face);
  6327. return;
  6328. }
  6329. const float stretch = computeStretch(m_mesh->position(vertex0), m_mesh->position(vertex1), m_mesh->position(freeVertex), texcoords[0], texcoords[1], texcoords[2]);
  6330. if (stretch >= FLT_MAX) {
  6331. m_faceInvalid.set(face);
  6332. return;
  6333. }
  6334. const float cost = fabsf(stretch - 1.0f);
  6335. if (cost > 0.5f) {
  6336. m_faceInvalid.set(face);
  6337. return;
  6338. }
  6339. // Add the candidate.
  6340. Candidate *candidate = XA_ALLOC(MemTag::Default, Candidate);
  6341. candidate->face = face;
  6342. candidate->vertex = freeVertex;
  6343. candidate->position = texcoords[localFreeVertex];
  6344. candidate->prev = candidate->next = nullptr;
  6345. candidate->cost = candidate->maxCost = cost;
  6346. candidate->patchEdge = patchEdge;
  6347. candidate->patchVertexOrient = patchVertexOrient;
  6348. m_candidates.push_back(candidate);
  6349. m_faceToCandidate[face] = candidate;
  6350. // Link with candidates that share the same vertex. Append to tail.
  6351. for (uint32_t i = 0; i < m_candidates.size() - 1; i++) {
  6352. if (m_candidates[i]->vertex == candidate->vertex) {
  6353. Candidate *tail = m_candidates[i];
  6354. for (;;) {
  6355. if (tail->next)
  6356. tail = tail->next;
  6357. else
  6358. break;
  6359. }
  6360. candidate->prev = tail;
  6361. candidate->next = nullptr;
  6362. tail->next = candidate;
  6363. break;
  6364. }
  6365. }
  6366. // Set max cost for linked candidates.
  6367. Candidate *head = linkedCandidateHead(candidate);
  6368. float maxCost = 0.0f;
  6369. for (CandidateIterator it(head); !it.isDone(); it.advance())
  6370. maxCost = max(maxCost, it.current()->cost);
  6371. for (CandidateIterator it(head); !it.isDone(); it.advance())
  6372. it.current()->maxCost = maxCost;
  6373. }
  6374. Candidate *linkedCandidateHead(Candidate *candidate)
  6375. {
  6376. Candidate *current = candidate;
  6377. for (;;) {
  6378. if (!current->prev)
  6379. break;
  6380. current = current->prev;
  6381. }
  6382. return current;
  6383. }
  6384. void removeLinkedCandidates(Candidate *head)
  6385. {
  6386. XA_DEBUG_ASSERT(!head->prev);
  6387. Candidate *current = head;
  6388. while (current) {
  6389. Candidate *next = current->next;
  6390. m_faceToCandidate[current->face] = nullptr;
  6391. for (uint32_t i = 0; i < m_candidates.size(); i++) {
  6392. if (m_candidates[i] == current) {
  6393. m_candidates.removeAt(i);
  6394. break;
  6395. }
  6396. }
  6397. XA_FREE(current);
  6398. current = next;
  6399. }
  6400. }
  6401. void orthoProjectFace(uint32_t face, Vector2 *texcoords) const
  6402. {
  6403. const Vector3 normal = -m_mesh->computeFaceNormal(face);
  6404. const Vector3 tangent = normalize(m_mesh->position(m_mesh->vertexAt(face * 3 + 1)) - m_mesh->position(m_mesh->vertexAt(face * 3 + 0)));
  6405. const Vector3 bitangent = cross(normal, tangent);
  6406. for (uint32_t i = 0; i < 3; i++) {
  6407. const Vector3 &pos = m_mesh->position(m_mesh->vertexAt(face * 3 + i));
  6408. texcoords[i] = Vector2(dot(tangent, pos), dot(bitangent, pos));
  6409. }
  6410. }
  6411. float parametricArea(const Vector2 *texcoords) const
  6412. {
  6413. const Vector2 &v1 = texcoords[0];
  6414. const Vector2 &v2 = texcoords[1];
  6415. const Vector2 &v3 = texcoords[2];
  6416. return ((v2.x - v1.x) * (v3.y - v1.y) - (v3.x - v1.x) * (v2.y - v1.y)) * 0.5f;
  6417. }
  6418. float computeStretch(Vector3 p1, Vector3 p2, Vector3 p3, Vector2 t1, Vector2 t2, Vector2 t3) const
  6419. {
  6420. float parametricArea = ((t2.y - t1.y) * (t3.x - t1.x) - (t3.y - t1.y) * (t2.x - t1.x)) * 0.5f;
  6421. if (isZero(parametricArea, kAreaEpsilon))
  6422. return FLT_MAX;
  6423. if (parametricArea < 0.0f)
  6424. parametricArea = fabsf(parametricArea);
  6425. const float geometricArea = length(cross(p2 - p1, p3 - p1)) * 0.5f;
  6426. if (parametricArea <= geometricArea)
  6427. return parametricArea / geometricArea;
  6428. else
  6429. return geometricArea / parametricArea;
  6430. }
  6431. // Return value is positive if the point is one side of the edge, negative if on the other side.
  6432. float orientToEdge(Vector2 edgeVertex0, Vector2 edgeVertex1, Vector2 point) const
  6433. {
  6434. return (edgeVertex0.x - point.x) * (edgeVertex1.y - point.y) - (edgeVertex0.y - point.y) * (edgeVertex1.x - point.x);
  6435. }
  6436. };
  6437. // Estimate quality of existing parameterization.
  6438. struct Quality
  6439. {
  6440. // computeBoundaryIntersection
  6441. bool boundaryIntersection = false;
  6442. // computeFlippedFaces
  6443. uint32_t totalTriangleCount = 0;
  6444. uint32_t flippedTriangleCount = 0;
  6445. uint32_t zeroAreaTriangleCount = 0;
  6446. // computeMetrics
  6447. float totalParametricArea = 0.0f;
  6448. float totalGeometricArea = 0.0f;
  6449. float stretchMetric = 0.0f;
  6450. float maxStretchMetric = 0.0f;
  6451. float conformalMetric = 0.0f;
  6452. float authalicMetric = 0.0f;
  6453. void computeBoundaryIntersection(const Mesh *mesh, UniformGrid2 &boundaryGrid)
  6454. {
  6455. const Array<uint32_t> &boundaryEdges = mesh->boundaryEdges();
  6456. const uint32_t boundaryEdgeCount = boundaryEdges.size();
  6457. boundaryGrid.reset(mesh->texcoords(), mesh->indices(), boundaryEdgeCount);
  6458. for (uint32_t i = 0; i < boundaryEdgeCount; i++)
  6459. boundaryGrid.append(boundaryEdges[i]);
  6460. boundaryIntersection = boundaryGrid.intersect(mesh->epsilon());
  6461. #if XA_DEBUG_EXPORT_BOUNDARY_GRID
  6462. static int exportIndex = 0;
  6463. char filename[256];
  6464. XA_SPRINTF(filename, sizeof(filename), "debug_boundary_grid_%03d.tga", exportIndex);
  6465. boundaryGrid.debugExport(filename);
  6466. exportIndex++;
  6467. #endif
  6468. }
  6469. void computeFlippedFaces(const Mesh *mesh, Array<uint32_t> *flippedFaces)
  6470. {
  6471. totalTriangleCount = flippedTriangleCount = zeroAreaTriangleCount = 0;
  6472. if (flippedFaces)
  6473. flippedFaces->clear();
  6474. const uint32_t faceCount = mesh->faceCount();
  6475. for (uint32_t f = 0; f < faceCount; f++) {
  6476. Vector2 texcoord[3];
  6477. for (int i = 0; i < 3; i++) {
  6478. const uint32_t v = mesh->vertexAt(f * 3 + i);
  6479. texcoord[i] = mesh->texcoord(v);
  6480. }
  6481. totalTriangleCount++;
  6482. const float t1 = texcoord[0].x;
  6483. const float s1 = texcoord[0].y;
  6484. const float t2 = texcoord[1].x;
  6485. const float s2 = texcoord[1].y;
  6486. const float t3 = texcoord[2].x;
  6487. const float s3 = texcoord[2].y;
  6488. const float parametricArea = ((s2 - s1) * (t3 - t1) - (s3 - s1) * (t2 - t1)) * 0.5f;
  6489. if (isZero(parametricArea, kAreaEpsilon)) {
  6490. zeroAreaTriangleCount++;
  6491. continue;
  6492. }
  6493. if (parametricArea < 0.0f) {
  6494. // Count flipped triangles.
  6495. flippedTriangleCount++;
  6496. if (flippedFaces)
  6497. flippedFaces->push_back(f);
  6498. }
  6499. }
  6500. if (flippedTriangleCount + zeroAreaTriangleCount == totalTriangleCount) {
  6501. // If all triangles are flipped, then none are.
  6502. if (flippedFaces)
  6503. flippedFaces->clear();
  6504. flippedTriangleCount = 0;
  6505. }
  6506. if (flippedTriangleCount > totalTriangleCount / 2)
  6507. {
  6508. // If more than half the triangles are flipped, reverse the flipped / not flipped classification.
  6509. flippedTriangleCount = totalTriangleCount - flippedTriangleCount;
  6510. if (flippedFaces) {
  6511. Array<uint32_t> temp;
  6512. flippedFaces->copyTo(temp);
  6513. flippedFaces->clear();
  6514. for (uint32_t f = 0; f < faceCount; f++) {
  6515. bool match = false;
  6516. for (uint32_t ff = 0; ff < temp.size(); ff++) {
  6517. if (temp[ff] == f) {
  6518. match = true;
  6519. break;
  6520. }
  6521. }
  6522. if (!match)
  6523. flippedFaces->push_back(f);
  6524. }
  6525. }
  6526. }
  6527. }
  6528. void computeMetrics(const Mesh *mesh)
  6529. {
  6530. totalGeometricArea = totalParametricArea = 0.0f;
  6531. stretchMetric = maxStretchMetric = conformalMetric = authalicMetric = 0.0f;
  6532. const uint32_t faceCount = mesh->faceCount();
  6533. for (uint32_t f = 0; f < faceCount; f++) {
  6534. Vector3 pos[3];
  6535. Vector2 texcoord[3];
  6536. for (int i = 0; i < 3; i++) {
  6537. const uint32_t v = mesh->vertexAt(f * 3 + i);
  6538. pos[i] = mesh->position(v);
  6539. texcoord[i] = mesh->texcoord(v);
  6540. }
  6541. // Evaluate texture stretch metric. See:
  6542. // - "Texture Mapping Progressive Meshes", Sander, Snyder, Gortler & Hoppe
  6543. // - "Mesh Parameterization: Theory and Practice", Siggraph'07 Course Notes, Hormann, Levy & Sheffer.
  6544. const float t1 = texcoord[0].x;
  6545. const float s1 = texcoord[0].y;
  6546. const float t2 = texcoord[1].x;
  6547. const float s2 = texcoord[1].y;
  6548. const float t3 = texcoord[2].x;
  6549. const float s3 = texcoord[2].y;
  6550. float parametricArea = ((s2 - s1) * (t3 - t1) - (s3 - s1) * (t2 - t1)) * 0.5f;
  6551. if (isZero(parametricArea, kAreaEpsilon))
  6552. continue;
  6553. if (parametricArea < 0.0f)
  6554. parametricArea = fabsf(parametricArea);
  6555. const float geometricArea = length(cross(pos[1] - pos[0], pos[2] - pos[0])) / 2;
  6556. const Vector3 Ss = (pos[0] * (t2 - t3) + pos[1] * (t3 - t1) + pos[2] * (t1 - t2)) / (2 * parametricArea);
  6557. const Vector3 St = (pos[0] * (s3 - s2) + pos[1] * (s1 - s3) + pos[2] * (s2 - s1)) / (2 * parametricArea);
  6558. const float a = dot(Ss, Ss); // E
  6559. const float b = dot(Ss, St); // F
  6560. const float c = dot(St, St); // G
  6561. // Compute eigen-values of the first fundamental form:
  6562. const float sigma1 = sqrtf(0.5f * max(0.0f, a + c - sqrtf(square(a - c) + 4 * square(b)))); // gamma uppercase, min eigenvalue.
  6563. const float sigma2 = sqrtf(0.5f * max(0.0f, a + c + sqrtf(square(a - c) + 4 * square(b)))); // gamma lowercase, max eigenvalue.
  6564. XA_ASSERT(sigma2 > sigma1 || equal(sigma1, sigma2, kEpsilon));
  6565. // isometric: sigma1 = sigma2 = 1
  6566. // conformal: sigma1 / sigma2 = 1
  6567. // authalic: sigma1 * sigma2 = 1
  6568. const float rmsStretch = sqrtf((a + c) * 0.5f);
  6569. const float rmsStretch2 = sqrtf((square(sigma1) + square(sigma2)) * 0.5f);
  6570. XA_DEBUG_ASSERT(equal(rmsStretch, rmsStretch2, 0.01f));
  6571. XA_UNUSED(rmsStretch2);
  6572. stretchMetric += square(rmsStretch) * geometricArea;
  6573. maxStretchMetric = max(maxStretchMetric, sigma2);
  6574. if (!isZero(sigma1, 0.000001f)) {
  6575. // sigma1 is zero when geometricArea is zero.
  6576. conformalMetric += (sigma2 / sigma1) * geometricArea;
  6577. }
  6578. authalicMetric += (sigma1 * sigma2) * geometricArea;
  6579. // Accumulate total areas.
  6580. totalGeometricArea += geometricArea;
  6581. totalParametricArea += parametricArea;
  6582. }
  6583. XA_DEBUG_ASSERT(isFinite(totalParametricArea) && totalParametricArea >= 0);
  6584. XA_DEBUG_ASSERT(isFinite(totalGeometricArea) && totalGeometricArea >= 0);
  6585. XA_DEBUG_ASSERT(isFinite(stretchMetric));
  6586. XA_DEBUG_ASSERT(isFinite(maxStretchMetric));
  6587. XA_DEBUG_ASSERT(isFinite(conformalMetric));
  6588. XA_DEBUG_ASSERT(isFinite(authalicMetric));
  6589. if (totalGeometricArea > 0.0f) {
  6590. const float normFactor = sqrtf(totalParametricArea / totalGeometricArea);
  6591. stretchMetric = sqrtf(stretchMetric / totalGeometricArea) * normFactor;
  6592. maxStretchMetric *= normFactor;
  6593. conformalMetric = sqrtf(conformalMetric / totalGeometricArea);
  6594. authalicMetric = sqrtf(authalicMetric / totalGeometricArea);
  6595. }
  6596. }
  6597. };
  6598. struct ChartCtorBuffers
  6599. {
  6600. Array<uint32_t> chartMeshIndices;
  6601. Array<uint32_t> unifiedMeshIndices;
  6602. };
  6603. class Chart
  6604. {
  6605. public:
  6606. Chart(const Basis &basis, segment::ChartGeneratorType::Enum generatorType, ConstArrayView<uint32_t> faces, const Mesh *sourceMesh, uint32_t chartGroupId, uint32_t chartId) : m_basis(basis), m_unifiedMesh(nullptr), m_type(ChartType::LSCM), m_generatorType(generatorType), m_tjunctionCount(0), m_originalVertexCount(0), m_isInvalid(false)
  6607. {
  6608. XA_UNUSED(chartGroupId);
  6609. XA_UNUSED(chartId);
  6610. m_faceToSourceFaceMap.copyFrom(faces.data, faces.length);
  6611. const uint32_t approxVertexCount = min(faces.length * 3, sourceMesh->vertexCount());
  6612. m_unifiedMesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, sourceMesh->epsilon(), approxVertexCount, faces.length);
  6613. HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToUnifiedVertexMap(MemTag::Mesh, approxVertexCount), sourceVertexToChartVertexMap(MemTag::Mesh, approxVertexCount);
  6614. m_originalIndices.resize(faces.length * 3);
  6615. // Add geometry.
  6616. const uint32_t faceCount = faces.length;
  6617. for (uint32_t f = 0; f < faceCount; f++) {
  6618. uint32_t unifiedIndices[3];
  6619. for (uint32_t i = 0; i < 3; i++) {
  6620. const uint32_t sourceVertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
  6621. uint32_t sourceUnifiedVertex = sourceMesh->firstColocalVertex(sourceVertex);
  6622. if (m_generatorType == segment::ChartGeneratorType::OriginalUv && sourceVertex != sourceUnifiedVertex) {
  6623. // Original UVs: don't unify vertices with different UVs; we want to preserve UVs.
  6624. if (!equal(sourceMesh->texcoord(sourceVertex), sourceMesh->texcoord(sourceUnifiedVertex), sourceMesh->epsilon()))
  6625. sourceUnifiedVertex = sourceVertex;
  6626. }
  6627. uint32_t unifiedVertex = sourceVertexToUnifiedVertexMap.get(sourceUnifiedVertex);
  6628. if (unifiedVertex == UINT32_MAX) {
  6629. unifiedVertex = sourceVertexToUnifiedVertexMap.add(sourceUnifiedVertex);
  6630. m_unifiedMesh->addVertex(sourceMesh->position(sourceVertex), Vector3(0.0f), sourceMesh->texcoord(sourceVertex));
  6631. }
  6632. if (sourceVertexToChartVertexMap.get(sourceVertex) == UINT32_MAX) {
  6633. sourceVertexToChartVertexMap.add(sourceVertex);
  6634. m_vertexToSourceVertexMap.push_back(sourceVertex);
  6635. m_chartVertexToUnifiedVertexMap.push_back(unifiedVertex);
  6636. m_originalVertexCount++;
  6637. }
  6638. m_originalIndices[f * 3 + i] = sourceVertexToChartVertexMap.get(sourceVertex);;
  6639. XA_DEBUG_ASSERT(m_originalIndices[f * 3 + i] != UINT32_MAX);
  6640. unifiedIndices[i] = sourceVertexToUnifiedVertexMap.get(sourceUnifiedVertex);
  6641. XA_DEBUG_ASSERT(unifiedIndices[i] != UINT32_MAX);
  6642. }
  6643. m_unifiedMesh->addFace(unifiedIndices);
  6644. }
  6645. m_unifiedMesh->createBoundaries();
  6646. if (m_generatorType == segment::ChartGeneratorType::Planar) {
  6647. m_type = ChartType::Planar;
  6648. return;
  6649. }
  6650. #if XA_CHECK_T_JUNCTIONS
  6651. m_tjunctionCount = meshCheckTJunctions(*m_unifiedMesh);
  6652. #if XA_DEBUG_EXPORT_OBJ_TJUNCTION
  6653. if (m_tjunctionCount > 0) {
  6654. char filename[256];
  6655. XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_chart_%03u_tjunction.obj", sourceMesh->id(), chartGroupId, chartId);
  6656. m_unifiedMesh->writeObjFile(filename);
  6657. }
  6658. #endif
  6659. #endif
  6660. }
  6661. Chart(ChartCtorBuffers &buffers, const Chart *parent, const Mesh *parentMesh, ConstArrayView<uint32_t> faces, ConstArrayView<Vector2> texcoords, const Mesh *sourceMesh) : m_unifiedMesh(nullptr), m_type(ChartType::Piecewise), m_generatorType(segment::ChartGeneratorType::Piecewise), m_tjunctionCount(0), m_originalVertexCount(0), m_isInvalid(false)
  6662. {
  6663. const uint32_t faceCount = faces.length;
  6664. m_faceToSourceFaceMap.resize(faceCount);
  6665. for (uint32_t i = 0; i < faceCount; i++)
  6666. m_faceToSourceFaceMap[i] = parent->m_faceToSourceFaceMap[faces[i]]; // Map faces to parent chart source mesh.
  6667. // Copy face indices.
  6668. Array<uint32_t> &chartMeshIndices = buffers.chartMeshIndices;
  6669. chartMeshIndices.resize(sourceMesh->vertexCount());
  6670. chartMeshIndices.fillBytes(0xff);
  6671. m_unifiedMesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, sourceMesh->epsilon(), m_faceToSourceFaceMap.size() * 3, m_faceToSourceFaceMap.size());
  6672. HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToUnifiedVertexMap(MemTag::Mesh, m_faceToSourceFaceMap.size() * 3);
  6673. // Add vertices.
  6674. for (uint32_t f = 0; f < faceCount; f++) {
  6675. for (uint32_t i = 0; i < 3; i++) {
  6676. const uint32_t vertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
  6677. const uint32_t sourceUnifiedVertex = sourceMesh->firstColocalVertex(vertex);
  6678. const uint32_t parentVertex = parentMesh->vertexAt(faces[f] * 3 + i);
  6679. uint32_t unifiedVertex = sourceVertexToUnifiedVertexMap.get(sourceUnifiedVertex);
  6680. if (unifiedVertex == UINT32_MAX) {
  6681. unifiedVertex = sourceVertexToUnifiedVertexMap.add(sourceUnifiedVertex);
  6682. m_unifiedMesh->addVertex(sourceMesh->position(vertex), Vector3(0.0f), texcoords[parentVertex]);
  6683. }
  6684. if (chartMeshIndices[vertex] == UINT32_MAX) {
  6685. chartMeshIndices[vertex] = m_originalVertexCount;
  6686. m_originalVertexCount++;
  6687. m_vertexToSourceVertexMap.push_back(vertex);
  6688. m_chartVertexToUnifiedVertexMap.push_back(unifiedVertex);
  6689. }
  6690. }
  6691. }
  6692. // Add faces.
  6693. m_originalIndices.resize(faceCount * 3);
  6694. for (uint32_t f = 0; f < faceCount; f++) {
  6695. uint32_t unifiedIndices[3];
  6696. for (uint32_t i = 0; i < 3; i++) {
  6697. const uint32_t vertex = sourceMesh->vertexAt(m_faceToSourceFaceMap[f] * 3 + i);
  6698. m_originalIndices[f * 3 + i] = chartMeshIndices[vertex];
  6699. const uint32_t unifiedVertex = sourceMesh->firstColocalVertex(vertex);
  6700. unifiedIndices[i] = sourceVertexToUnifiedVertexMap.get(unifiedVertex);
  6701. }
  6702. m_unifiedMesh->addFace(unifiedIndices);
  6703. }
  6704. m_unifiedMesh->createBoundaries();
  6705. // Need to store texcoords for backup/restore so packing can be run multiple times.
  6706. backupTexcoords();
  6707. }
  6708. ~Chart()
  6709. {
  6710. if (m_unifiedMesh) {
  6711. m_unifiedMesh->~Mesh();
  6712. XA_FREE(m_unifiedMesh);
  6713. m_unifiedMesh = nullptr;
  6714. }
  6715. }
  6716. bool isInvalid() const { return m_isInvalid; }
  6717. ChartType type() const { return m_type; }
  6718. segment::ChartGeneratorType::Enum generatorType() const { return m_generatorType; }
  6719. uint32_t tjunctionCount() const { return m_tjunctionCount; }
  6720. const Quality &quality() const { return m_quality; }
  6721. #if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
  6722. const Array<uint32_t> &paramFlippedFaces() const { return m_paramFlippedFaces; }
  6723. #endif
  6724. uint32_t mapFaceToSourceFace(uint32_t i) const { return m_faceToSourceFaceMap[i]; }
  6725. uint32_t mapChartVertexToSourceVertex(uint32_t i) const { return m_vertexToSourceVertexMap[i]; }
  6726. const Mesh *unifiedMesh() const { return m_unifiedMesh; }
  6727. Mesh *unifiedMesh() { return m_unifiedMesh; }
  6728. // Vertex count of the chart mesh before unifying vertices.
  6729. uint32_t originalVertexCount() const { return m_originalVertexCount; }
  6730. uint32_t originalVertexToUnifiedVertex(uint32_t v) const { return m_chartVertexToUnifiedVertexMap[v]; }
  6731. ConstArrayView<uint32_t> originalVertices() const { return m_originalIndices; }
  6732. void parameterize(const ChartOptions &options, UniformGrid2 &boundaryGrid)
  6733. {
  6734. const uint32_t unifiedVertexCount = m_unifiedMesh->vertexCount();
  6735. if (m_generatorType == segment::ChartGeneratorType::OriginalUv) {
  6736. } else {
  6737. // Project vertices to plane.
  6738. XA_PROFILE_START(parameterizeChartsOrthogonal)
  6739. for (uint32_t i = 0; i < unifiedVertexCount; i++)
  6740. m_unifiedMesh->texcoord(i) = Vector2(dot(m_basis.tangent, m_unifiedMesh->position(i)), dot(m_basis.bitangent, m_unifiedMesh->position(i)));
  6741. XA_PROFILE_END(parameterizeChartsOrthogonal)
  6742. // Computing charts checks for flipped triangles and boundary intersection. Don't need to do that again here if chart is planar.
  6743. if (m_type != ChartType::Planar && m_generatorType != segment::ChartGeneratorType::OriginalUv) {
  6744. XA_PROFILE_START(parameterizeChartsEvaluateQuality)
  6745. m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
  6746. m_quality.computeFlippedFaces(m_unifiedMesh, nullptr);
  6747. m_quality.computeMetrics(m_unifiedMesh);
  6748. XA_PROFILE_END(parameterizeChartsEvaluateQuality)
  6749. // Use orthogonal parameterization if quality is acceptable.
  6750. if (!m_quality.boundaryIntersection && m_quality.flippedTriangleCount == 0 && m_quality.zeroAreaTriangleCount == 0 && m_quality.totalGeometricArea > 0.0f && m_quality.stretchMetric <= 1.1f && m_quality.maxStretchMetric <= 1.25f)
  6751. m_type = ChartType::Ortho;
  6752. }
  6753. if (m_type == ChartType::LSCM) {
  6754. XA_PROFILE_START(parameterizeChartsLSCM)
  6755. if (options.paramFunc) {
  6756. options.paramFunc(&m_unifiedMesh->position(0).x, &m_unifiedMesh->texcoord(0).x, m_unifiedMesh->vertexCount(), m_unifiedMesh->indices().data, m_unifiedMesh->indexCount());
  6757. }
  6758. else
  6759. computeLeastSquaresConformalMap(m_unifiedMesh);
  6760. XA_PROFILE_END(parameterizeChartsLSCM)
  6761. XA_PROFILE_START(parameterizeChartsEvaluateQuality)
  6762. m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
  6763. #if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
  6764. m_quality.computeFlippedFaces(m_unifiedMesh, &m_paramFlippedFaces);
  6765. #else
  6766. m_quality.computeFlippedFaces(m_unifiedMesh, nullptr);
  6767. #endif
  6768. // Don't need to call computeMetrics here, that's only used in evaluateOrthoQuality to determine if quality is acceptable enough to use ortho projection.
  6769. if (m_quality.boundaryIntersection || m_quality.flippedTriangleCount > 0 || m_quality.zeroAreaTriangleCount > 0)
  6770. m_isInvalid = true;
  6771. XA_PROFILE_END(parameterizeChartsEvaluateQuality)
  6772. }
  6773. }
  6774. if (options.fixWinding && m_unifiedMesh->computeFaceParametricArea(0) < 0.0f) {
  6775. for (uint32_t i = 0; i < unifiedVertexCount; i++)
  6776. m_unifiedMesh->texcoord(i).x *= -1.0f;
  6777. }
  6778. #if XA_CHECK_PARAM_WINDING
  6779. const uint32_t faceCount = m_unifiedMesh->faceCount();
  6780. uint32_t flippedCount = 0;
  6781. for (uint32_t i = 0; i < faceCount; i++) {
  6782. const float area = m_unifiedMesh->computeFaceParametricArea(i);
  6783. if (area < 0.0f)
  6784. flippedCount++;
  6785. }
  6786. if (flippedCount == faceCount) {
  6787. XA_PRINT_WARNING("param: all faces flipped\n");
  6788. } else if (flippedCount > 0) {
  6789. XA_PRINT_WARNING("param: %u / %u faces flipped\n", flippedCount, faceCount);
  6790. }
  6791. #endif
  6792. #if XA_DEBUG_ALL_CHARTS_INVALID
  6793. m_isInvalid = true;
  6794. #endif
  6795. // Need to store texcoords for backup/restore so packing can be run multiple times.
  6796. backupTexcoords();
  6797. }
  6798. Vector2 computeParametricBounds() const
  6799. {
  6800. Vector2 minCorner(FLT_MAX, FLT_MAX);
  6801. Vector2 maxCorner(-FLT_MAX, -FLT_MAX);
  6802. const uint32_t vertexCount = m_unifiedMesh->vertexCount();
  6803. for (uint32_t v = 0; v < vertexCount; v++) {
  6804. minCorner = min(minCorner, m_unifiedMesh->texcoord(v));
  6805. maxCorner = max(maxCorner, m_unifiedMesh->texcoord(v));
  6806. }
  6807. return (maxCorner - minCorner) * 0.5f;
  6808. }
  6809. #if XA_CHECK_PIECEWISE_CHART_QUALITY
  6810. void evaluateQuality(UniformGrid2 &boundaryGrid)
  6811. {
  6812. m_quality.computeBoundaryIntersection(m_unifiedMesh, boundaryGrid);
  6813. #if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
  6814. m_quality.computeFlippedFaces(m_unifiedMesh, &m_paramFlippedFaces);
  6815. #else
  6816. m_quality.computeFlippedFaces(m_unifiedMesh, nullptr);
  6817. #endif
  6818. if (m_quality.boundaryIntersection || m_quality.flippedTriangleCount > 0 || m_quality.zeroAreaTriangleCount > 0)
  6819. m_isInvalid = true;
  6820. }
  6821. #endif
  6822. void restoreTexcoords()
  6823. {
  6824. memcpy(m_unifiedMesh->texcoords().data, m_backupTexcoords.data(), m_unifiedMesh->vertexCount() * sizeof(Vector2));
  6825. }
  6826. private:
  6827. void backupTexcoords()
  6828. {
  6829. m_backupTexcoords.resize(m_unifiedMesh->vertexCount());
  6830. memcpy(m_backupTexcoords.data(), m_unifiedMesh->texcoords().data, m_unifiedMesh->vertexCount() * sizeof(Vector2));
  6831. }
  6832. Basis m_basis;
  6833. Mesh *m_unifiedMesh;
  6834. ChartType m_type;
  6835. segment::ChartGeneratorType::Enum m_generatorType;
  6836. uint32_t m_tjunctionCount;
  6837. uint32_t m_originalVertexCount;
  6838. Array<uint32_t> m_originalIndices;
  6839. // List of faces of the source mesh that belong to this chart.
  6840. Array<uint32_t> m_faceToSourceFaceMap;
  6841. // Map vertices of the chart mesh to vertices of the source mesh.
  6842. Array<uint32_t> m_vertexToSourceVertexMap;
  6843. Array<uint32_t> m_chartVertexToUnifiedVertexMap;
  6844. Array<Vector2> m_backupTexcoords;
  6845. Quality m_quality;
  6846. #if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
  6847. Array<uint32_t> m_paramFlippedFaces;
  6848. #endif
  6849. bool m_isInvalid;
  6850. };
  6851. struct CreateAndParameterizeChartTaskGroupArgs
  6852. {
  6853. Progress *progress;
  6854. ThreadLocal<UniformGrid2> *boundaryGrid;
  6855. ThreadLocal<ChartCtorBuffers> *chartBuffers;
  6856. const ChartOptions *options;
  6857. ThreadLocal<PiecewiseParam> *pp;
  6858. };
  6859. struct CreateAndParameterizeChartTaskArgs
  6860. {
  6861. const Basis *basis;
  6862. Chart *chart; // output
  6863. Array<Chart *> charts; // output (if more than one chart)
  6864. segment::ChartGeneratorType::Enum chartGeneratorType;
  6865. const Mesh *mesh;
  6866. ConstArrayView<uint32_t> faces;
  6867. uint32_t chartGroupId;
  6868. uint32_t chartId;
  6869. };
  6870. static void runCreateAndParameterizeChartTask(void *groupUserData, void *taskUserData)
  6871. {
  6872. XA_PROFILE_START(createChartMeshAndParameterizeThread)
  6873. auto groupArgs = (CreateAndParameterizeChartTaskGroupArgs *)groupUserData;
  6874. auto args = (CreateAndParameterizeChartTaskArgs *)taskUserData;
  6875. XA_PROFILE_START(createChartMesh)
  6876. args->chart = XA_NEW_ARGS(MemTag::Default, Chart, *args->basis, args->chartGeneratorType, args->faces, args->mesh, args->chartGroupId, args->chartId);
  6877. XA_PROFILE_END(createChartMesh)
  6878. XA_PROFILE_START(parameterizeCharts)
  6879. args->chart->parameterize(*groupArgs->options, groupArgs->boundaryGrid->get());
  6880. XA_PROFILE_END(parameterizeCharts)
  6881. #if XA_RECOMPUTE_CHARTS
  6882. if (!args->chart->isInvalid()) {
  6883. XA_PROFILE_END(createChartMeshAndParameterizeThread)
  6884. return;
  6885. }
  6886. // Recompute charts with invalid parameterizations.
  6887. XA_PROFILE_START(parameterizeChartsRecompute)
  6888. Chart *invalidChart = args->chart;
  6889. const Mesh *invalidMesh = invalidChart->unifiedMesh();
  6890. PiecewiseParam &pp = groupArgs->pp->get();
  6891. pp.reset(invalidMesh);
  6892. #if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
  6893. char filename[256];
  6894. XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_chart_%03u_recomputed.obj", args->mesh->id(), args->chartGroupId, args->chartId);
  6895. FILE *file;
  6896. XA_FOPEN(file, filename, "w");
  6897. uint32_t subChartIndex = 0;
  6898. #endif
  6899. for (;;) {
  6900. XA_PROFILE_START(parameterizeChartsPiecewise)
  6901. const bool facesRemaining = pp.computeChart();
  6902. XA_PROFILE_END(parameterizeChartsPiecewise)
  6903. if (!facesRemaining)
  6904. break;
  6905. Chart *chart = XA_NEW_ARGS(MemTag::Default, Chart, groupArgs->chartBuffers->get(), invalidChart, invalidMesh, pp.chartFaces(), pp.texcoords(), args->mesh);
  6906. #if XA_CHECK_PIECEWISE_CHART_QUALITY
  6907. chart->evaluateQuality(args->boundaryGrid->get());
  6908. #endif
  6909. args->charts.push_back(chart);
  6910. #if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
  6911. if (file) {
  6912. for (uint32_t j = 0; j < invalidMesh->vertexCount(); j++) {
  6913. fprintf(file, "v %g %g %g\n", invalidMesh->position(j).x, invalidMesh->position(j).y, invalidMesh->position(j).z);
  6914. fprintf(file, "vt %g %g\n", pp.texcoords()[j].x, pp.texcoords()[j].y);
  6915. }
  6916. fprintf(file, "o chart%03u\n", subChartIndex);
  6917. fprintf(file, "s off\n");
  6918. for (uint32_t f = 0; f < pp.chartFaces().length; f++) {
  6919. fprintf(file, "f ");
  6920. const uint32_t face = pp.chartFaces()[f];
  6921. for (uint32_t j = 0; j < 3; j++) {
  6922. const uint32_t index = invalidMesh->vertexCount() * subChartIndex + invalidMesh->vertexAt(face * 3 + j) + 1; // 1-indexed
  6923. fprintf(file, "%d/%d/%c", index, index, j == 2 ? '\n' : ' ');
  6924. }
  6925. }
  6926. }
  6927. subChartIndex++;
  6928. #endif
  6929. }
  6930. #if XA_DEBUG_EXPORT_OBJ_RECOMPUTED_CHARTS
  6931. if (file)
  6932. fclose(file);
  6933. #endif
  6934. XA_PROFILE_END(parameterizeChartsRecompute)
  6935. #endif // XA_RECOMPUTE_CHARTS
  6936. XA_PROFILE_END(createChartMeshAndParameterizeThread)
  6937. // Update progress.
  6938. groupArgs->progress->increment(args->faces.length);
  6939. }
  6940. // Set of charts corresponding to mesh faces in the same face group.
  6941. class ChartGroup
  6942. {
  6943. public:
  6944. ChartGroup(uint32_t id, const Mesh *sourceMesh, const MeshFaceGroups *sourceMeshFaceGroups, MeshFaceGroups::Handle faceGroup) : m_id(id), m_sourceMesh(sourceMesh), m_sourceMeshFaceGroups(sourceMeshFaceGroups), m_faceGroup(faceGroup)
  6945. {
  6946. }
  6947. ~ChartGroup()
  6948. {
  6949. for (uint32_t i = 0; i < m_charts.size(); i++) {
  6950. m_charts[i]->~Chart();
  6951. XA_FREE(m_charts[i]);
  6952. }
  6953. }
  6954. uint32_t chartCount() const { return m_charts.size(); }
  6955. Chart *chartAt(uint32_t i) const { return m_charts[i]; }
  6956. uint32_t faceCount() const { return m_sourceMeshFaceGroups->faceCount(m_faceGroup); }
  6957. void computeCharts(TaskScheduler *taskScheduler, const ChartOptions &options, Progress *progress, segment::Atlas &atlas, ThreadLocal<UniformGrid2> *boundaryGrid, ThreadLocal<ChartCtorBuffers> *chartBuffers, ThreadLocal<PiecewiseParam> *piecewiseParam)
  6958. {
  6959. // This function may be called multiple times, so destroy existing charts.
  6960. for (uint32_t i = 0; i < m_charts.size(); i++) {
  6961. m_charts[i]->~Chart();
  6962. XA_FREE(m_charts[i]);
  6963. }
  6964. // Create mesh from source mesh, using only the faces in this face group.
  6965. XA_PROFILE_START(createChartGroupMesh)
  6966. Mesh *mesh = createMesh();
  6967. XA_PROFILE_END(createChartGroupMesh)
  6968. // Segment mesh into charts (arrays of faces).
  6969. #if XA_DEBUG_SINGLE_CHART
  6970. XA_UNUSED(options);
  6971. XA_UNUSED(atlas);
  6972. const uint32_t chartCount = 1;
  6973. uint32_t offset;
  6974. Basis chartBasis;
  6975. Fit::computeBasis(&mesh->position(0), mesh->vertexCount(), &chartBasis);
  6976. Array<uint32_t> chartFaces;
  6977. chartFaces.resize(1 + mesh->faceCount());
  6978. chartFaces[0] = mesh->faceCount();
  6979. for (uint32_t i = 0; i < chartFaces.size() - 1; i++)
  6980. chartFaces[i + 1] = m_faceToSourceFaceMap[i];
  6981. // Destroy mesh.
  6982. const uint32_t faceCount = mesh->faceCount();
  6983. mesh->~Mesh();
  6984. XA_FREE(mesh);
  6985. #else
  6986. XA_PROFILE_START(buildAtlas)
  6987. atlas.reset(mesh, options);
  6988. atlas.compute();
  6989. XA_PROFILE_END(buildAtlas)
  6990. // Update progress.
  6991. progress->increment(faceCount());
  6992. #if XA_DEBUG_EXPORT_OBJ_CHARTS
  6993. char filename[256];
  6994. XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u_charts.obj", m_sourceMesh->id(), m_id);
  6995. FILE *file;
  6996. XA_FOPEN(file, filename, "w");
  6997. if (file) {
  6998. mesh->writeObjVertices(file);
  6999. for (uint32_t i = 0; i < atlas.chartCount(); i++) {
  7000. fprintf(file, "o chart_%04d\n", i);
  7001. fprintf(file, "s off\n");
  7002. ConstArrayView<uint32_t> faces = atlas.chartFaces(i);
  7003. for (uint32_t f = 0; f < faces.length; f++)
  7004. mesh->writeObjFace(file, faces[f]);
  7005. }
  7006. mesh->writeObjBoundaryEges(file);
  7007. fclose(file);
  7008. }
  7009. #endif
  7010. // Destroy mesh.
  7011. const uint32_t faceCount = mesh->faceCount();
  7012. mesh->~Mesh();
  7013. XA_FREE(mesh);
  7014. XA_PROFILE_START(copyChartFaces)
  7015. if (progress->cancel)
  7016. return;
  7017. // Copy faces from segment::Atlas to m_chartFaces array with <chart 0 face count> <face 0> <face n> <chart 1 face count> etc. encoding.
  7018. // segment::Atlas faces refer to the chart group mesh. Map them to the input mesh instead.
  7019. const uint32_t chartCount = atlas.chartCount();
  7020. Array<uint32_t> chartFaces;
  7021. chartFaces.resize(chartCount + faceCount);
  7022. uint32_t offset = 0;
  7023. for (uint32_t i = 0; i < chartCount; i++) {
  7024. ConstArrayView<uint32_t> faces = atlas.chartFaces(i);
  7025. chartFaces[offset++] = faces.length;
  7026. for (uint32_t j = 0; j < faces.length; j++)
  7027. chartFaces[offset++] = m_faceToSourceFaceMap[faces[j]];
  7028. }
  7029. XA_PROFILE_END(copyChartFaces)
  7030. #endif
  7031. XA_PROFILE_START(createChartMeshAndParameterizeReal)
  7032. CreateAndParameterizeChartTaskGroupArgs groupArgs;
  7033. groupArgs.progress = progress;
  7034. groupArgs.boundaryGrid = boundaryGrid;
  7035. groupArgs.chartBuffers = chartBuffers;
  7036. groupArgs.options = &options;
  7037. groupArgs.pp = piecewiseParam;
  7038. TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(&groupArgs, chartCount);
  7039. Array<CreateAndParameterizeChartTaskArgs> taskArgs;
  7040. taskArgs.resize(chartCount);
  7041. taskArgs.runCtors(); // Has Array member.
  7042. offset = 0;
  7043. for (uint32_t i = 0; i < chartCount; i++) {
  7044. CreateAndParameterizeChartTaskArgs &args = taskArgs[i];
  7045. #if XA_DEBUG_SINGLE_CHART
  7046. args.basis = &chartBasis;
  7047. args.isPlanar = false;
  7048. #else
  7049. args.basis = &atlas.chartBasis(i);
  7050. args.chartGeneratorType = atlas.chartGeneratorType(i);
  7051. #endif
  7052. args.chart = nullptr;
  7053. args.chartGroupId = m_id;
  7054. args.chartId = i;
  7055. const uint32_t chartFaceCount = chartFaces[offset++];
  7056. args.faces = ConstArrayView<uint32_t>(&chartFaces[offset], chartFaceCount);
  7057. offset += chartFaceCount;
  7058. args.mesh = m_sourceMesh;
  7059. Task task;
  7060. task.userData = &args;
  7061. task.func = runCreateAndParameterizeChartTask;
  7062. taskScheduler->run(taskGroup, task);
  7063. }
  7064. taskScheduler->wait(&taskGroup);
  7065. XA_PROFILE_END(createChartMeshAndParameterizeReal)
  7066. #if XA_RECOMPUTE_CHARTS
  7067. // Count charts. Skip invalid ones and include new ones added by recomputing.
  7068. uint32_t newChartCount = 0;
  7069. for (uint32_t i = 0; i < chartCount; i++) {
  7070. if (taskArgs[i].chart->isInvalid())
  7071. newChartCount += taskArgs[i].charts.size();
  7072. else
  7073. newChartCount++;
  7074. }
  7075. m_charts.resize(newChartCount);
  7076. // Add valid charts first. Destroy invalid ones.
  7077. uint32_t current = 0;
  7078. for (uint32_t i = 0; i < chartCount; i++) {
  7079. Chart *chart = taskArgs[i].chart;
  7080. if (chart->isInvalid()) {
  7081. chart->~Chart();
  7082. XA_FREE(chart);
  7083. continue;
  7084. }
  7085. m_charts[current++] = chart;
  7086. }
  7087. // Now add new charts.
  7088. for (uint32_t i = 0; i < chartCount; i++) {
  7089. CreateAndParameterizeChartTaskArgs &args = taskArgs[i];
  7090. for (uint32_t j = 0; j < args.charts.size(); j++)
  7091. m_charts[current++] = args.charts[j];
  7092. }
  7093. #else // XA_RECOMPUTE_CHARTS
  7094. m_charts.resize(chartCount);
  7095. for (uint32_t i = 0; i < chartCount; i++)
  7096. m_charts[i] = taskArgs[i].chart;
  7097. #endif // XA_RECOMPUTE_CHARTS
  7098. taskArgs.runDtors(); // Has Array member.
  7099. }
  7100. private:
  7101. Mesh *createMesh()
  7102. {
  7103. XA_DEBUG_ASSERT(m_faceGroup != MeshFaceGroups::kInvalid);
  7104. // Create new mesh from the source mesh, using faces that belong to this group.
  7105. m_faceToSourceFaceMap.reserve(m_sourceMeshFaceGroups->faceCount(m_faceGroup));
  7106. for (MeshFaceGroups::Iterator it(m_sourceMeshFaceGroups, m_faceGroup); !it.isDone(); it.advance())
  7107. m_faceToSourceFaceMap.push_back(it.face());
  7108. // Only initial meshes has ignored faces. The only flag we care about is HasNormals.
  7109. const uint32_t faceCount = m_faceToSourceFaceMap.size();
  7110. XA_DEBUG_ASSERT(faceCount > 0);
  7111. const uint32_t approxVertexCount = min(faceCount * 3, m_sourceMesh->vertexCount());
  7112. Mesh *mesh = XA_NEW_ARGS(MemTag::Mesh, Mesh, m_sourceMesh->epsilon(), approxVertexCount, faceCount, m_sourceMesh->flags() & MeshFlags::HasNormals);
  7113. HashMap<uint32_t, PassthroughHash<uint32_t>> sourceVertexToVertexMap(MemTag::Mesh, approxVertexCount);
  7114. for (uint32_t f = 0; f < faceCount; f++) {
  7115. const uint32_t face = m_faceToSourceFaceMap[f];
  7116. for (uint32_t i = 0; i < 3; i++) {
  7117. const uint32_t vertex = m_sourceMesh->vertexAt(face * 3 + i);
  7118. if (sourceVertexToVertexMap.get(vertex) == UINT32_MAX) {
  7119. sourceVertexToVertexMap.add(vertex);
  7120. Vector3 normal(0.0f);
  7121. if (m_sourceMesh->flags() & MeshFlags::HasNormals)
  7122. normal = m_sourceMesh->normal(vertex);
  7123. mesh->addVertex(m_sourceMesh->position(vertex), normal, m_sourceMesh->texcoord(vertex));
  7124. }
  7125. }
  7126. }
  7127. // Add faces.
  7128. for (uint32_t f = 0; f < faceCount; f++) {
  7129. const uint32_t face = m_faceToSourceFaceMap[f];
  7130. XA_DEBUG_ASSERT(!m_sourceMesh->isFaceIgnored(face));
  7131. uint32_t indices[3];
  7132. for (uint32_t i = 0; i < 3; i++) {
  7133. const uint32_t vertex = m_sourceMesh->vertexAt(face * 3 + i);
  7134. indices[i] = sourceVertexToVertexMap.get(vertex);
  7135. XA_DEBUG_ASSERT(indices[i] != UINT32_MAX);
  7136. }
  7137. // Don't copy flags - ignored faces aren't used by chart groups, they are handled by InvalidMeshGeometry.
  7138. mesh->addFace(indices);
  7139. }
  7140. XA_PROFILE_START(createChartGroupMeshColocals)
  7141. mesh->createColocals();
  7142. XA_PROFILE_END(createChartGroupMeshColocals)
  7143. XA_PROFILE_START(createChartGroupMeshBoundaries)
  7144. mesh->createBoundaries();
  7145. mesh->destroyEdgeMap(); // Only needed it for createBoundaries.
  7146. XA_PROFILE_END(createChartGroupMeshBoundaries)
  7147. #if XA_DEBUG_EXPORT_OBJ_CHART_GROUPS
  7148. char filename[256];
  7149. XA_SPRINTF(filename, sizeof(filename), "debug_mesh_%03u_chartgroup_%03u.obj", m_sourceMesh->id(), m_id);
  7150. mesh->writeObjFile(filename);
  7151. #endif
  7152. return mesh;
  7153. }
  7154. const uint32_t m_id;
  7155. const Mesh * const m_sourceMesh;
  7156. const MeshFaceGroups * const m_sourceMeshFaceGroups;
  7157. const MeshFaceGroups::Handle m_faceGroup;
  7158. Array<uint32_t> m_faceToSourceFaceMap; // List of faces of the source mesh that belong to this chart group.
  7159. Array<Chart *> m_charts;
  7160. };
  7161. struct ChartGroupComputeChartsTaskGroupArgs
  7162. {
  7163. ThreadLocal<segment::Atlas> *atlas;
  7164. const ChartOptions *options;
  7165. Progress *progress;
  7166. TaskScheduler *taskScheduler;
  7167. ThreadLocal<UniformGrid2> *boundaryGrid;
  7168. ThreadLocal<ChartCtorBuffers> *chartBuffers;
  7169. ThreadLocal<PiecewiseParam> *piecewiseParam;
  7170. };
  7171. static void runChartGroupComputeChartsTask(void *groupUserData, void *taskUserData)
  7172. {
  7173. auto args = (ChartGroupComputeChartsTaskGroupArgs *)groupUserData;
  7174. auto chartGroup = (ChartGroup *)taskUserData;
  7175. if (args->progress->cancel)
  7176. return;
  7177. XA_PROFILE_START(chartGroupComputeChartsThread)
  7178. chartGroup->computeCharts(args->taskScheduler, *args->options, args->progress, args->atlas->get(), args->boundaryGrid, args->chartBuffers, args->piecewiseParam);
  7179. XA_PROFILE_END(chartGroupComputeChartsThread)
  7180. }
  7181. struct MeshComputeChartsTaskGroupArgs
  7182. {
  7183. ThreadLocal<segment::Atlas> *atlas;
  7184. const ChartOptions *options;
  7185. Progress *progress;
  7186. TaskScheduler *taskScheduler;
  7187. ThreadLocal<UniformGrid2> *boundaryGrid;
  7188. ThreadLocal<ChartCtorBuffers> *chartBuffers;
  7189. ThreadLocal<PiecewiseParam> *piecewiseParam;
  7190. };
  7191. struct MeshComputeChartsTaskArgs
  7192. {
  7193. const Mesh *sourceMesh;
  7194. Array<ChartGroup *> *chartGroups; // output
  7195. InvalidMeshGeometry *invalidMeshGeometry; // output
  7196. };
  7197. #if XA_DEBUG_EXPORT_OBJ_FACE_GROUPS
  7198. static uint32_t s_faceGroupsCurrentVertex = 0;
  7199. #endif
  7200. static void runMeshComputeChartsTask(void *groupUserData, void *taskUserData)
  7201. {
  7202. auto groupArgs = (MeshComputeChartsTaskGroupArgs *)groupUserData;
  7203. auto args = (MeshComputeChartsTaskArgs *)taskUserData;
  7204. if (groupArgs->progress->cancel)
  7205. return;
  7206. XA_PROFILE_START(computeChartsThread)
  7207. // Create face groups.
  7208. XA_PROFILE_START(createFaceGroups)
  7209. MeshFaceGroups *meshFaceGroups = XA_NEW_ARGS(MemTag::Mesh, MeshFaceGroups, args->sourceMesh);
  7210. meshFaceGroups->compute();
  7211. const uint32_t chartGroupCount = meshFaceGroups->groupCount();
  7212. XA_PROFILE_END(createFaceGroups)
  7213. if (groupArgs->progress->cancel)
  7214. goto cleanup;
  7215. #if XA_DEBUG_EXPORT_OBJ_FACE_GROUPS
  7216. {
  7217. static std::mutex s_mutex;
  7218. std::lock_guard<std::mutex> lock(s_mutex);
  7219. char filename[256];
  7220. XA_SPRINTF(filename, sizeof(filename), "debug_face_groups.obj");
  7221. FILE *file;
  7222. XA_FOPEN(file, filename, s_faceGroupsCurrentVertex == 0 ? "w" : "a");
  7223. if (file) {
  7224. const Mesh *mesh = args->sourceMesh;
  7225. mesh->writeObjVertices(file);
  7226. // groups
  7227. uint32_t numGroups = 0;
  7228. for (uint32_t i = 0; i < mesh->faceCount(); i++) {
  7229. if (meshFaceGroups->groupAt(i) != MeshFaceGroups::kInvalid)
  7230. numGroups = max(numGroups, meshFaceGroups->groupAt(i) + 1);
  7231. }
  7232. for (uint32_t i = 0; i < numGroups; i++) {
  7233. fprintf(file, "o mesh_%03u_group_%04d\n", mesh->id(), i);
  7234. fprintf(file, "s off\n");
  7235. for (uint32_t f = 0; f < mesh->faceCount(); f++) {
  7236. if (meshFaceGroups->groupAt(f) == i)
  7237. mesh->writeObjFace(file, f, s_faceGroupsCurrentVertex);
  7238. }
  7239. }
  7240. fprintf(file, "o mesh_%03u_group_ignored\n", mesh->id());
  7241. fprintf(file, "s off\n");
  7242. for (uint32_t f = 0; f < mesh->faceCount(); f++) {
  7243. if (meshFaceGroups->groupAt(f) == MeshFaceGroups::kInvalid)
  7244. mesh->writeObjFace(file, f, s_faceGroupsCurrentVertex);
  7245. }
  7246. mesh->writeObjBoundaryEges(file);
  7247. s_faceGroupsCurrentVertex += mesh->vertexCount();
  7248. fclose(file);
  7249. }
  7250. }
  7251. #endif
  7252. // Create a chart group for each face group.
  7253. args->chartGroups->resize(chartGroupCount);
  7254. for (uint32_t i = 0; i < chartGroupCount; i++)
  7255. (*args->chartGroups)[i] = XA_NEW_ARGS(MemTag::Default, ChartGroup, i, args->sourceMesh, meshFaceGroups, MeshFaceGroups::Handle(i));
  7256. // Extract invalid geometry via the invalid face group (MeshFaceGroups::kInvalid).
  7257. {
  7258. XA_PROFILE_START(extractInvalidMeshGeometry)
  7259. args->invalidMeshGeometry->extract(args->sourceMesh, meshFaceGroups);
  7260. XA_PROFILE_END(extractInvalidMeshGeometry)
  7261. }
  7262. // One task for each chart group - compute charts.
  7263. {
  7264. XA_PROFILE_START(chartGroupComputeChartsReal)
  7265. // Sort chart groups by face count.
  7266. Array<float> chartGroupSortData;
  7267. chartGroupSortData.resize(chartGroupCount);
  7268. for (uint32_t i = 0; i < chartGroupCount; i++)
  7269. chartGroupSortData[i] = (float)(*args->chartGroups)[i]->faceCount();
  7270. RadixSort chartGroupSort;
  7271. chartGroupSort.sort(chartGroupSortData);
  7272. // Larger chart groups are added first to reduce the chance of thread starvation.
  7273. ChartGroupComputeChartsTaskGroupArgs taskGroupArgs;
  7274. taskGroupArgs.atlas = groupArgs->atlas;
  7275. taskGroupArgs.options = groupArgs->options;
  7276. taskGroupArgs.progress = groupArgs->progress;
  7277. taskGroupArgs.taskScheduler = groupArgs->taskScheduler;
  7278. taskGroupArgs.boundaryGrid = groupArgs->boundaryGrid;
  7279. taskGroupArgs.chartBuffers = groupArgs->chartBuffers;
  7280. taskGroupArgs.piecewiseParam = groupArgs->piecewiseParam;
  7281. TaskGroupHandle taskGroup = groupArgs->taskScheduler->createTaskGroup(&taskGroupArgs, chartGroupCount);
  7282. for (uint32_t i = 0; i < chartGroupCount; i++) {
  7283. Task task;
  7284. task.userData = (*args->chartGroups)[chartGroupCount - i - 1];
  7285. task.func = runChartGroupComputeChartsTask;
  7286. groupArgs->taskScheduler->run(taskGroup, task);
  7287. }
  7288. groupArgs->taskScheduler->wait(&taskGroup);
  7289. XA_PROFILE_END(chartGroupComputeChartsReal)
  7290. }
  7291. XA_PROFILE_END(computeChartsThread)
  7292. cleanup:
  7293. if (meshFaceGroups) {
  7294. meshFaceGroups->~MeshFaceGroups();
  7295. XA_FREE(meshFaceGroups);
  7296. }
  7297. }
  7298. /// An atlas is a set of chart groups.
  7299. class Atlas
  7300. {
  7301. public:
  7302. Atlas() : m_chartsComputed(false) {}
  7303. ~Atlas()
  7304. {
  7305. for (uint32_t i = 0; i < m_meshChartGroups.size(); i++) {
  7306. for (uint32_t j = 0; j < m_meshChartGroups[i].size(); j++) {
  7307. m_meshChartGroups[i][j]->~ChartGroup();
  7308. XA_FREE(m_meshChartGroups[i][j]);
  7309. }
  7310. }
  7311. m_meshChartGroups.runDtors();
  7312. m_invalidMeshGeometry.runDtors();
  7313. }
  7314. uint32_t meshCount() const { return m_meshes.size(); }
  7315. const InvalidMeshGeometry &invalidMeshGeometry(uint32_t meshIndex) const { return m_invalidMeshGeometry[meshIndex]; }
  7316. bool chartsComputed() const { return m_chartsComputed; }
  7317. uint32_t chartGroupCount(uint32_t mesh) const { return m_meshChartGroups[mesh].size(); }
  7318. const ChartGroup *chartGroupAt(uint32_t mesh, uint32_t group) const { return m_meshChartGroups[mesh][group]; }
  7319. void addMesh(const Mesh *mesh)
  7320. {
  7321. m_meshes.push_back(mesh);
  7322. }
  7323. bool computeCharts(TaskScheduler *taskScheduler, const ChartOptions &options, ProgressFunc progressFunc, void *progressUserData)
  7324. {
  7325. XA_PROFILE_START(computeChartsReal)
  7326. #if XA_DEBUG_EXPORT_OBJ_PLANAR_REGIONS
  7327. segment::s_planarRegionsCurrentRegion = segment::s_planarRegionsCurrentVertex = 0;
  7328. #endif
  7329. // Progress is per-face x 2 (1 for chart faces, 1 for parameterized chart faces).
  7330. const uint32_t meshCount = m_meshes.size();
  7331. uint32_t totalFaceCount = 0;
  7332. for (uint32_t i = 0; i < meshCount; i++)
  7333. totalFaceCount += m_meshes[i]->faceCount();
  7334. Progress progress(ProgressCategory::ComputeCharts, progressFunc, progressUserData, totalFaceCount * 2);
  7335. m_chartsComputed = false;
  7336. // Clear chart groups, since this function may be called multiple times.
  7337. if (!m_meshChartGroups.isEmpty()) {
  7338. for (uint32_t i = 0; i < m_meshChartGroups.size(); i++) {
  7339. for (uint32_t j = 0; j < m_meshChartGroups[i].size(); j++) {
  7340. m_meshChartGroups[i][j]->~ChartGroup();
  7341. XA_FREE(m_meshChartGroups[i][j]);
  7342. }
  7343. m_meshChartGroups[i].clear();
  7344. }
  7345. XA_ASSERT(m_meshChartGroups.size() == meshCount); // The number of meshes shouldn't have changed.
  7346. }
  7347. m_meshChartGroups.resize(meshCount);
  7348. m_meshChartGroups.runCtors();
  7349. m_invalidMeshGeometry.resize(meshCount);
  7350. m_invalidMeshGeometry.runCtors();
  7351. // One task per mesh.
  7352. Array<MeshComputeChartsTaskArgs> taskArgs;
  7353. taskArgs.resize(meshCount);
  7354. for (uint32_t i = 0; i < meshCount; i++) {
  7355. MeshComputeChartsTaskArgs &args = taskArgs[i];
  7356. args.sourceMesh = m_meshes[i];
  7357. args.chartGroups = &m_meshChartGroups[i];
  7358. args.invalidMeshGeometry = &m_invalidMeshGeometry[i];
  7359. }
  7360. // Sort meshes by indexCount.
  7361. Array<float> meshSortData;
  7362. meshSortData.resize(meshCount);
  7363. for (uint32_t i = 0; i < meshCount; i++)
  7364. meshSortData[i] = (float)m_meshes[i]->indexCount();
  7365. RadixSort meshSort;
  7366. meshSort.sort(meshSortData);
  7367. // Larger meshes are added first to reduce the chance of thread starvation.
  7368. ThreadLocal<segment::Atlas> atlas;
  7369. ThreadLocal<UniformGrid2> boundaryGrid; // For Quality boundary intersection.
  7370. ThreadLocal<ChartCtorBuffers> chartBuffers;
  7371. ThreadLocal<PiecewiseParam> piecewiseParam;
  7372. MeshComputeChartsTaskGroupArgs taskGroupArgs;
  7373. taskGroupArgs.atlas = &atlas;
  7374. taskGroupArgs.options = &options;
  7375. taskGroupArgs.progress = &progress;
  7376. taskGroupArgs.taskScheduler = taskScheduler;
  7377. taskGroupArgs.boundaryGrid = &boundaryGrid;
  7378. taskGroupArgs.chartBuffers = &chartBuffers;
  7379. taskGroupArgs.piecewiseParam = &piecewiseParam;
  7380. TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(&taskGroupArgs, meshCount);
  7381. for (uint32_t i = 0; i < meshCount; i++) {
  7382. Task task;
  7383. task.userData = &taskArgs[meshSort.ranks()[meshCount - i - 1]];
  7384. task.func = runMeshComputeChartsTask;
  7385. taskScheduler->run(taskGroup, task);
  7386. }
  7387. taskScheduler->wait(&taskGroup);
  7388. XA_PROFILE_END(computeChartsReal)
  7389. if (progress.cancel)
  7390. return false;
  7391. m_chartsComputed = true;
  7392. return true;
  7393. }
  7394. private:
  7395. Array<const Mesh *> m_meshes;
  7396. Array<InvalidMeshGeometry> m_invalidMeshGeometry; // 1 per mesh.
  7397. Array<Array<ChartGroup *> > m_meshChartGroups;
  7398. bool m_chartsComputed;
  7399. };
  7400. } // namespace param
  7401. namespace pack {
  7402. class AtlasImage
  7403. {
  7404. public:
  7405. AtlasImage(uint32_t width, uint32_t height) : m_width(width), m_height(height)
  7406. {
  7407. m_data.resize(m_width * m_height);
  7408. memset(m_data.data(), 0, sizeof(uint32_t) * m_data.size());
  7409. }
  7410. void resize(uint32_t width, uint32_t height)
  7411. {
  7412. Array<uint32_t> data;
  7413. data.resize(width * height);
  7414. memset(data.data(), 0, sizeof(uint32_t) * data.size());
  7415. for (uint32_t y = 0; y < min(m_height, height); y++)
  7416. memcpy(&data[y * width], &m_data[y * m_width], min(m_width, width) * sizeof(uint32_t));
  7417. m_width = width;
  7418. m_height = height;
  7419. data.moveTo(m_data);
  7420. }
  7421. void addChart(uint32_t chartIndex, const BitImage *image, const BitImage *imageBilinear, const BitImage *imagePadding, int atlas_w, int atlas_h, int offset_x, int offset_y)
  7422. {
  7423. const int w = image->width();
  7424. const int h = image->height();
  7425. for (int y = 0; y < h; y++) {
  7426. const int yy = y + offset_y;
  7427. if (yy < 0)
  7428. continue;
  7429. for (int x = 0; x < w; x++) {
  7430. const int xx = x + offset_x;
  7431. if (xx >= 0 && xx < atlas_w && yy < atlas_h) {
  7432. const uint32_t dataOffset = xx + yy * m_width;
  7433. if (image->get(x, y)) {
  7434. XA_DEBUG_ASSERT(m_data[dataOffset] == 0);
  7435. m_data[dataOffset] = chartIndex | kImageHasChartIndexBit;
  7436. } else if (imageBilinear && imageBilinear->get(x, y)) {
  7437. XA_DEBUG_ASSERT(m_data[dataOffset] == 0);
  7438. m_data[dataOffset] = chartIndex | kImageHasChartIndexBit | kImageIsBilinearBit;
  7439. } else if (imagePadding && imagePadding->get(x, y)) {
  7440. XA_DEBUG_ASSERT(m_data[dataOffset] == 0);
  7441. m_data[dataOffset] = chartIndex | kImageHasChartIndexBit | kImageIsPaddingBit;
  7442. }
  7443. }
  7444. }
  7445. }
  7446. }
  7447. void copyTo(uint32_t *dest, uint32_t destWidth, uint32_t destHeight, int padding) const
  7448. {
  7449. for (uint32_t y = 0; y < destHeight; y++)
  7450. memcpy(&dest[y * destWidth], &m_data[padding + (y + padding) * m_width], destWidth * sizeof(uint32_t));
  7451. }
  7452. #if XA_DEBUG_EXPORT_ATLAS_IMAGES
  7453. void writeTga(const char *filename, uint32_t width, uint32_t height) const
  7454. {
  7455. Array<uint8_t> image;
  7456. image.resize(width * height * 3);
  7457. for (uint32_t y = 0; y < height; y++) {
  7458. if (y >= m_height)
  7459. continue;
  7460. for (uint32_t x = 0; x < width; x++) {
  7461. if (x >= m_width)
  7462. continue;
  7463. const uint32_t data = m_data[x + y * m_width];
  7464. uint8_t *bgr = &image[(x + y * width) * 3];
  7465. if (data == 0) {
  7466. bgr[0] = bgr[1] = bgr[2] = 0;
  7467. continue;
  7468. }
  7469. const uint32_t chartIndex = data & kImageChartIndexMask;
  7470. if (data & kImageIsPaddingBit) {
  7471. bgr[0] = 0;
  7472. bgr[1] = 0;
  7473. bgr[2] = 255;
  7474. } else if (data & kImageIsBilinearBit) {
  7475. bgr[0] = 0;
  7476. bgr[1] = 255;
  7477. bgr[2] = 0;
  7478. } else {
  7479. const int mix = 192;
  7480. srand((unsigned int)chartIndex);
  7481. bgr[0] = uint8_t((rand() % 255 + mix) * 0.5f);
  7482. bgr[1] = uint8_t((rand() % 255 + mix) * 0.5f);
  7483. bgr[2] = uint8_t((rand() % 255 + mix) * 0.5f);
  7484. }
  7485. }
  7486. }
  7487. WriteTga(filename, image.data(), width, height);
  7488. }
  7489. #endif
  7490. private:
  7491. uint32_t m_width, m_height;
  7492. Array<uint32_t> m_data;
  7493. };
  7494. struct Chart
  7495. {
  7496. int32_t atlasIndex;
  7497. uint32_t material;
  7498. ConstArrayView<uint32_t> indices;
  7499. float parametricArea;
  7500. float surfaceArea;
  7501. ArrayView<Vector2> vertices;
  7502. Array<uint32_t> uniqueVertices;
  7503. // bounding box
  7504. Vector2 majorAxis, minorAxis, minCorner, maxCorner;
  7505. // Mesh only
  7506. const Array<uint32_t> *boundaryEdges;
  7507. // UvMeshChart only
  7508. Array<uint32_t> faces;
  7509. Vector2 &uniqueVertexAt(uint32_t v) { return uniqueVertices.isEmpty() ? vertices[v] : vertices[uniqueVertices[v]]; }
  7510. uint32_t uniqueVertexCount() const { return uniqueVertices.isEmpty() ? vertices.length : uniqueVertices.size(); }
  7511. };
  7512. struct AddChartTaskArgs
  7513. {
  7514. param::Chart *paramChart;
  7515. Chart *chart; // out
  7516. };
  7517. static void runAddChartTask(void *groupUserData, void *taskUserData)
  7518. {
  7519. XA_PROFILE_START(packChartsAddChartsThread)
  7520. auto boundingBox = (ThreadLocal<BoundingBox2D> *)groupUserData;
  7521. auto args = (AddChartTaskArgs *)taskUserData;
  7522. param::Chart *paramChart = args->paramChart;
  7523. XA_PROFILE_START(packChartsAddChartsRestoreTexcoords)
  7524. paramChart->restoreTexcoords();
  7525. XA_PROFILE_END(packChartsAddChartsRestoreTexcoords)
  7526. Mesh *mesh = paramChart->unifiedMesh();
  7527. Chart *chart = args->chart = XA_NEW(MemTag::Default, Chart);
  7528. chart->atlasIndex = -1;
  7529. chart->material = 0;
  7530. chart->indices = mesh->indices();
  7531. chart->parametricArea = mesh->computeParametricArea();
  7532. if (chart->parametricArea < kAreaEpsilon) {
  7533. // When the parametric area is too small we use a rough approximation to prevent divisions by very small numbers.
  7534. const Vector2 bounds = paramChart->computeParametricBounds();
  7535. chart->parametricArea = bounds.x * bounds.y;
  7536. }
  7537. chart->surfaceArea = mesh->computeSurfaceArea();
  7538. chart->vertices = mesh->texcoords();
  7539. chart->boundaryEdges = &mesh->boundaryEdges();
  7540. // Compute bounding box of chart.
  7541. BoundingBox2D &bb = boundingBox->get();
  7542. bb.clear();
  7543. for (uint32_t v = 0; v < chart->vertices.length; v++) {
  7544. if (mesh->isBoundaryVertex(v))
  7545. bb.appendBoundaryVertex(mesh->texcoord(v));
  7546. }
  7547. bb.compute(mesh->texcoords());
  7548. chart->majorAxis = bb.majorAxis;
  7549. chart->minorAxis = bb.minorAxis;
  7550. chart->minCorner = bb.minCorner;
  7551. chart->maxCorner = bb.maxCorner;
  7552. XA_PROFILE_END(packChartsAddChartsThread)
  7553. }
  7554. struct Atlas
  7555. {
  7556. ~Atlas()
  7557. {
  7558. for (uint32_t i = 0; i < m_atlasImages.size(); i++) {
  7559. m_atlasImages[i]->~AtlasImage();
  7560. XA_FREE(m_atlasImages[i]);
  7561. }
  7562. for (uint32_t i = 0; i < m_bitImages.size(); i++) {
  7563. m_bitImages[i]->~BitImage();
  7564. XA_FREE(m_bitImages[i]);
  7565. }
  7566. for (uint32_t i = 0; i < m_charts.size(); i++) {
  7567. m_charts[i]->~Chart();
  7568. XA_FREE(m_charts[i]);
  7569. }
  7570. }
  7571. uint32_t getWidth() const { return m_width; }
  7572. uint32_t getHeight() const { return m_height; }
  7573. uint32_t getNumAtlases() const { return m_bitImages.size(); }
  7574. float getTexelsPerUnit() const { return m_texelsPerUnit; }
  7575. const Chart *getChart(uint32_t index) const { return m_charts[index]; }
  7576. uint32_t getChartCount() const { return m_charts.size(); }
  7577. const Array<AtlasImage *> &getImages() const { return m_atlasImages; }
  7578. float getUtilization(uint32_t atlas) const { return m_utilization[atlas]; }
  7579. void addCharts(TaskScheduler *taskScheduler, param::Atlas *paramAtlas)
  7580. {
  7581. // Count charts.
  7582. uint32_t chartCount = 0;
  7583. for (uint32_t i = 0; i < paramAtlas->meshCount(); i++) {
  7584. const uint32_t chartGroupsCount = paramAtlas->chartGroupCount(i);
  7585. for (uint32_t j = 0; j < chartGroupsCount; j++) {
  7586. const param::ChartGroup *chartGroup = paramAtlas->chartGroupAt(i, j);
  7587. chartCount += chartGroup->chartCount();
  7588. }
  7589. }
  7590. if (chartCount == 0)
  7591. return;
  7592. // Run one task per chart.
  7593. ThreadLocal<BoundingBox2D> boundingBox;
  7594. TaskGroupHandle taskGroup = taskScheduler->createTaskGroup(&boundingBox, chartCount);
  7595. Array<AddChartTaskArgs> taskArgs;
  7596. taskArgs.resize(chartCount);
  7597. uint32_t chartIndex = 0;
  7598. for (uint32_t i = 0; i < paramAtlas->meshCount(); i++) {
  7599. const uint32_t chartGroupsCount = paramAtlas->chartGroupCount(i);
  7600. for (uint32_t j = 0; j < chartGroupsCount; j++) {
  7601. const param::ChartGroup *chartGroup = paramAtlas->chartGroupAt(i, j);
  7602. const uint32_t count = chartGroup->chartCount();
  7603. for (uint32_t k = 0; k < count; k++) {
  7604. AddChartTaskArgs &args = taskArgs[chartIndex];
  7605. args.paramChart = chartGroup->chartAt(k);
  7606. Task task;
  7607. task.userData = &taskArgs[chartIndex];
  7608. task.func = runAddChartTask;
  7609. taskScheduler->run(taskGroup, task);
  7610. chartIndex++;
  7611. }
  7612. }
  7613. }
  7614. taskScheduler->wait(&taskGroup);
  7615. // Get task output.
  7616. m_charts.resize(chartCount);
  7617. for (uint32_t i = 0; i < chartCount; i++)
  7618. m_charts[i] = taskArgs[i].chart;
  7619. }
  7620. void addUvMeshCharts(UvMeshInstance *mesh)
  7621. {
  7622. // Copy texcoords from mesh.
  7623. mesh->texcoords.resize(mesh->mesh->texcoords.size());
  7624. memcpy(mesh->texcoords.data(), mesh->mesh->texcoords.data(), mesh->texcoords.size() * sizeof(Vector2));
  7625. BitArray vertexUsed(mesh->texcoords.size());
  7626. BoundingBox2D boundingBox;
  7627. for (uint32_t c = 0; c < mesh->mesh->charts.size(); c++) {
  7628. UvMeshChart *uvChart = mesh->mesh->charts[c];
  7629. Chart *chart = XA_NEW(MemTag::Default, Chart);
  7630. chart->atlasIndex = -1;
  7631. chart->material = uvChart->material;
  7632. chart->indices = uvChart->indices;
  7633. chart->vertices = mesh->texcoords;
  7634. chart->boundaryEdges = nullptr;
  7635. chart->faces.resize(uvChart->faces.size());
  7636. memcpy(chart->faces.data(), uvChart->faces.data(), sizeof(uint32_t) * uvChart->faces.size());
  7637. // Find unique vertices.
  7638. vertexUsed.zeroOutMemory();
  7639. for (uint32_t i = 0; i < chart->indices.length; i++) {
  7640. const uint32_t vertex = chart->indices[i];
  7641. if (!vertexUsed.get(vertex)) {
  7642. vertexUsed.set(vertex);
  7643. chart->uniqueVertices.push_back(vertex);
  7644. }
  7645. }
  7646. // Compute parametric and surface areas.
  7647. chart->parametricArea = 0.0f;
  7648. for (uint32_t f = 0; f < chart->indices.length / 3; f++) {
  7649. const Vector2 &v1 = chart->vertices[chart->indices[f * 3 + 0]];
  7650. const Vector2 &v2 = chart->vertices[chart->indices[f * 3 + 1]];
  7651. const Vector2 &v3 = chart->vertices[chart->indices[f * 3 + 2]];
  7652. chart->parametricArea += fabsf(triangleArea(v1, v2, v3));
  7653. }
  7654. chart->parametricArea *= 0.5f;
  7655. if (chart->parametricArea < kAreaEpsilon) {
  7656. // When the parametric area is too small we use a rough approximation to prevent divisions by very small numbers.
  7657. Vector2 minCorner(FLT_MAX, FLT_MAX);
  7658. Vector2 maxCorner(-FLT_MAX, -FLT_MAX);
  7659. for (uint32_t v = 0; v < chart->uniqueVertexCount(); v++) {
  7660. minCorner = min(minCorner, chart->uniqueVertexAt(v));
  7661. maxCorner = max(maxCorner, chart->uniqueVertexAt(v));
  7662. }
  7663. const Vector2 bounds = (maxCorner - minCorner) * 0.5f;
  7664. chart->parametricArea = bounds.x * bounds.y;
  7665. }
  7666. XA_DEBUG_ASSERT(isFinite(chart->parametricArea));
  7667. XA_DEBUG_ASSERT(!isNan(chart->parametricArea));
  7668. chart->surfaceArea = chart->parametricArea; // Identical for UV meshes.
  7669. // Compute bounding box of chart.
  7670. // Using all unique vertices for simplicity, can compute real boundaries if this is too slow.
  7671. boundingBox.clear();
  7672. for (uint32_t v = 0; v < chart->uniqueVertexCount(); v++)
  7673. boundingBox.appendBoundaryVertex(chart->uniqueVertexAt(v));
  7674. boundingBox.compute();
  7675. chart->majorAxis = boundingBox.majorAxis;
  7676. chart->minorAxis = boundingBox.minorAxis;
  7677. chart->minCorner = boundingBox.minCorner;
  7678. chart->maxCorner = boundingBox.maxCorner;
  7679. m_charts.push_back(chart);
  7680. }
  7681. }
  7682. // Pack charts in the smallest possible rectangle.
  7683. bool packCharts(const PackOptions &options, ProgressFunc progressFunc, void *progressUserData)
  7684. {
  7685. if (progressFunc) {
  7686. if (!progressFunc(ProgressCategory::PackCharts, 0, progressUserData))
  7687. return false;
  7688. }
  7689. const uint32_t chartCount = m_charts.size();
  7690. XA_PRINT("Packing %u charts\n", chartCount);
  7691. if (chartCount == 0) {
  7692. if (progressFunc) {
  7693. if (!progressFunc(ProgressCategory::PackCharts, 100, progressUserData))
  7694. return false;
  7695. }
  7696. return true;
  7697. }
  7698. // Estimate resolution and/or texels per unit if not specified.
  7699. m_texelsPerUnit = options.texelsPerUnit;
  7700. uint32_t resolution = options.resolution > 0 ? options.resolution + options.padding * 2 : 0;
  7701. const uint32_t maxResolution = m_texelsPerUnit > 0.0f ? resolution : 0;
  7702. if (resolution <= 0 || m_texelsPerUnit <= 0) {
  7703. if (resolution <= 0 && m_texelsPerUnit <= 0)
  7704. resolution = 1024;
  7705. float meshArea = 0;
  7706. for (uint32_t c = 0; c < chartCount; c++)
  7707. meshArea += m_charts[c]->surfaceArea;
  7708. if (resolution <= 0) {
  7709. // Estimate resolution based on the mesh surface area and given texel scale.
  7710. const float texelCount = max(1.0f, meshArea * square(m_texelsPerUnit) / 0.75f); // Assume 75% utilization.
  7711. resolution = max(1u, nextPowerOfTwo(uint32_t(sqrtf(texelCount))));
  7712. }
  7713. if (m_texelsPerUnit <= 0) {
  7714. // Estimate a suitable texelsPerUnit to fit the given resolution.
  7715. const float texelCount = max(1.0f, meshArea / 0.75f); // Assume 75% utilization.
  7716. m_texelsPerUnit = sqrtf((resolution * resolution) / texelCount);
  7717. XA_PRINT(" Estimating texelsPerUnit as %g\n", m_texelsPerUnit);
  7718. }
  7719. }
  7720. Array<float> chartOrderArray;
  7721. chartOrderArray.resize(chartCount);
  7722. Array<Vector2> chartExtents;
  7723. chartExtents.resize(chartCount);
  7724. float minChartPerimeter = FLT_MAX, maxChartPerimeter = 0.0f;
  7725. for (uint32_t c = 0; c < chartCount; c++) {
  7726. Chart *chart = m_charts[c];
  7727. // Compute chart scale
  7728. float scale = 1.0f;
  7729. if (chart->parametricArea != 0.0f) {
  7730. scale = sqrtf(chart->surfaceArea / chart->parametricArea) * m_texelsPerUnit;
  7731. XA_ASSERT(isFinite(scale));
  7732. }
  7733. // Translate, rotate and scale vertices. Compute extents.
  7734. Vector2 minCorner(FLT_MAX, FLT_MAX);
  7735. if (!options.rotateChartsToAxis) {
  7736. for (uint32_t i = 0; i < chart->uniqueVertexCount(); i++)
  7737. minCorner = min(minCorner, chart->uniqueVertexAt(i));
  7738. }
  7739. Vector2 extents(0.0f);
  7740. for (uint32_t i = 0; i < chart->uniqueVertexCount(); i++) {
  7741. Vector2 &texcoord = chart->uniqueVertexAt(i);
  7742. if (options.rotateChartsToAxis) {
  7743. const float x = dot(texcoord, chart->majorAxis);
  7744. const float y = dot(texcoord, chart->minorAxis);
  7745. texcoord.x = x;
  7746. texcoord.y = y;
  7747. texcoord -= chart->minCorner;
  7748. } else {
  7749. texcoord -= minCorner;
  7750. }
  7751. texcoord *= scale;
  7752. XA_DEBUG_ASSERT(texcoord.x >= 0.0f && texcoord.y >= 0.0f);
  7753. XA_DEBUG_ASSERT(isFinite(texcoord.x) && isFinite(texcoord.y));
  7754. extents = max(extents, texcoord);
  7755. }
  7756. XA_DEBUG_ASSERT(extents.x >= 0 && extents.y >= 0);
  7757. // Scale the charts to use the entire texel area available. So, if the width is 0.1 we could scale it to 1 without increasing the lightmap usage and making a better use of it. In many cases this also improves the look of the seams, since vertices on the chart boundaries have more chances of being aligned with the texel centers.
  7758. if (extents.x > 0.0f && extents.y > 0.0f) {
  7759. // Block align: align all chart extents to 4x4 blocks, but taking padding and texel center offset into account.
  7760. const int blockAlignSizeOffset = options.padding * 2 + 1;
  7761. int width = ftoi_ceil(extents.x);
  7762. if (options.blockAlign)
  7763. width = align(width + blockAlignSizeOffset, 4) - blockAlignSizeOffset;
  7764. int height = ftoi_ceil(extents.y);
  7765. if (options.blockAlign)
  7766. height = align(height + blockAlignSizeOffset, 4) - blockAlignSizeOffset;
  7767. for (uint32_t v = 0; v < chart->uniqueVertexCount(); v++) {
  7768. Vector2 &texcoord = chart->uniqueVertexAt(v);
  7769. texcoord.x = texcoord.x / extents.x * (float)width;
  7770. texcoord.y = texcoord.y / extents.y * (float)height;
  7771. }
  7772. extents.x = (float)width;
  7773. extents.y = (float)height;
  7774. }
  7775. // Limit chart size, either to PackOptions::maxChartSize or maxResolution (if set), whichever is smaller.
  7776. // If limiting chart size to maxResolution, print a warning, since that may not be desirable to the user.
  7777. uint32_t maxChartSize = options.maxChartSize;
  7778. bool warnChartResized = false;
  7779. if (maxResolution > 0 && (maxChartSize == 0 || maxResolution < maxChartSize)) {
  7780. maxChartSize = maxResolution - options.padding * 2; // Don't include padding.
  7781. warnChartResized = true;
  7782. }
  7783. if (maxChartSize > 0) {
  7784. const float realMaxChartSize = (float)maxChartSize - 1.0f; // Aligning to texel centers increases texel footprint by 1.
  7785. if (extents.x > realMaxChartSize || extents.y > realMaxChartSize) {
  7786. if (warnChartResized)
  7787. XA_PRINT(" Resizing chart %u from %gx%g to %ux%u to fit atlas\n", c, extents.x, extents.y, maxChartSize, maxChartSize);
  7788. scale = realMaxChartSize / max(extents.x, extents.y);
  7789. for (uint32_t i = 0; i < chart->uniqueVertexCount(); i++) {
  7790. Vector2 &texcoord = chart->uniqueVertexAt(i);
  7791. texcoord = min(texcoord * scale, Vector2(realMaxChartSize));
  7792. }
  7793. }
  7794. }
  7795. // Align to texel centers and add padding offset.
  7796. extents.x = extents.y = 0.0f;
  7797. for (uint32_t v = 0; v < chart->uniqueVertexCount(); v++) {
  7798. Vector2 &texcoord = chart->uniqueVertexAt(v);
  7799. texcoord.x += 0.5f + options.padding;
  7800. texcoord.y += 0.5f + options.padding;
  7801. extents = max(extents, texcoord);
  7802. }
  7803. if (extents.x > resolution || extents.y > resolution)
  7804. XA_PRINT(" Chart %u extents are large (%gx%g)\n", c, extents.x, extents.y);
  7805. chartExtents[c] = extents;
  7806. chartOrderArray[c] = extents.x + extents.y; // Use perimeter for chart sort key.
  7807. minChartPerimeter = min(minChartPerimeter, chartOrderArray[c]);
  7808. maxChartPerimeter = max(maxChartPerimeter, chartOrderArray[c]);
  7809. }
  7810. // Sort charts by perimeter.
  7811. m_radix.sort(chartOrderArray);
  7812. const uint32_t *ranks = m_radix.ranks();
  7813. // Divide chart perimeter range into buckets.
  7814. const float chartPerimeterBucketSize = (maxChartPerimeter - minChartPerimeter) / 16.0f;
  7815. uint32_t currentChartBucket = 0;
  7816. Array<Vector2i> chartStartPositions; // per atlas
  7817. chartStartPositions.push_back(Vector2i(0, 0));
  7818. // Pack sorted charts.
  7819. #if XA_DEBUG_EXPORT_ATLAS_IMAGES
  7820. const bool createImage = true;
  7821. #else
  7822. const bool createImage = options.createImage;
  7823. #endif
  7824. // chartImage: result from conservative rasterization
  7825. // chartImageBilinear: chartImage plus any texels that would be sampled by bilinear filtering.
  7826. // chartImagePadding: either chartImage or chartImageBilinear depending on options, with a dilate filter applied options.padding times.
  7827. // Rotated versions swap x and y.
  7828. BitImage chartImage, chartImageBilinear, chartImagePadding;
  7829. BitImage chartImageRotated, chartImageBilinearRotated, chartImagePaddingRotated;
  7830. UniformGrid2 boundaryEdgeGrid;
  7831. Array<Vector2i> atlasSizes;
  7832. atlasSizes.push_back(Vector2i(0, 0));
  7833. int progress = 0;
  7834. for (uint32_t i = 0; i < chartCount; i++) {
  7835. uint32_t c = ranks[chartCount - i - 1]; // largest chart first
  7836. Chart *chart = m_charts[c];
  7837. // @@ Add special cases for dot and line charts. @@ Lightmap rasterizer also needs to handle these special cases.
  7838. // @@ We could also have a special case for chart quads. If the quad surface <= 4 texels, align vertices with texel centers and do not add padding. May be very useful for foliage.
  7839. // @@ In general we could reduce the padding of all charts by one texel by using a rasterizer that takes into account the 2-texel footprint of the tent bilinear filter. For example,
  7840. // if we have a chart that is less than 1 texel wide currently we add one texel to the left and one texel to the right creating a 3-texel-wide bitImage. However, if we know that the
  7841. // chart is only 1 texel wide we could align it so that it only touches the footprint of two texels:
  7842. // | | <- Touches texels 0, 1 and 2.
  7843. // | | <- Only touches texels 0 and 1.
  7844. // \ \ / \ / /
  7845. // \ X X /
  7846. // \ / \ / \ /
  7847. // V V V
  7848. // 0 1 2
  7849. XA_PROFILE_START(packChartsRasterize)
  7850. // Resize and clear (discard = true) chart images.
  7851. // Leave room for padding at extents.
  7852. chartImage.resize(ftoi_ceil(chartExtents[c].x) + options.padding, ftoi_ceil(chartExtents[c].y) + options.padding, true);
  7853. if (options.rotateCharts)
  7854. chartImageRotated.resize(chartImage.height(), chartImage.width(), true);
  7855. if (options.bilinear) {
  7856. chartImageBilinear.resize(chartImage.width(), chartImage.height(), true);
  7857. if (options.rotateCharts)
  7858. chartImageBilinearRotated.resize(chartImage.height(), chartImage.width(), true);
  7859. }
  7860. // Rasterize chart faces.
  7861. const uint32_t faceCount = chart->indices.length / 3;
  7862. for (uint32_t f = 0; f < faceCount; f++) {
  7863. Vector2 vertices[3];
  7864. for (uint32_t v = 0; v < 3; v++)
  7865. vertices[v] = chart->vertices[chart->indices[f * 3 + v]];
  7866. DrawTriangleCallbackArgs args;
  7867. args.chartBitImage = &chartImage;
  7868. args.chartBitImageRotated = options.rotateCharts ? &chartImageRotated : nullptr;
  7869. raster::drawTriangle(Vector2((float)chartImage.width(), (float)chartImage.height()), vertices, drawTriangleCallback, &args);
  7870. }
  7871. // Expand chart by pixels sampled by bilinear interpolation.
  7872. if (options.bilinear)
  7873. bilinearExpand(chart, &chartImage, &chartImageBilinear, options.rotateCharts ? &chartImageBilinearRotated : nullptr, boundaryEdgeGrid);
  7874. // Expand chart by padding pixels (dilation).
  7875. if (options.padding > 0) {
  7876. // Copy into the same BitImage instances for every chart to avoid reallocating BitImage buffers (largest chart is packed first).
  7877. XA_PROFILE_START(packChartsDilate)
  7878. if (options.bilinear)
  7879. chartImageBilinear.copyTo(chartImagePadding);
  7880. else
  7881. chartImage.copyTo(chartImagePadding);
  7882. chartImagePadding.dilate(options.padding);
  7883. if (options.rotateCharts) {
  7884. if (options.bilinear)
  7885. chartImageBilinearRotated.copyTo(chartImagePaddingRotated);
  7886. else
  7887. chartImageRotated.copyTo(chartImagePaddingRotated);
  7888. chartImagePaddingRotated.dilate(options.padding);
  7889. }
  7890. XA_PROFILE_END(packChartsDilate)
  7891. }
  7892. XA_PROFILE_END(packChartsRasterize)
  7893. // Update brute force bucketing.
  7894. if (options.bruteForce) {
  7895. if (chartOrderArray[c] > minChartPerimeter && chartOrderArray[c] <= maxChartPerimeter - (chartPerimeterBucketSize * (currentChartBucket + 1))) {
  7896. // Moved to a smaller bucket, reset start location.
  7897. for (uint32_t j = 0; j < chartStartPositions.size(); j++)
  7898. chartStartPositions[j] = Vector2i(0, 0);
  7899. currentChartBucket++;
  7900. }
  7901. }
  7902. // Find a location to place the chart in the atlas.
  7903. BitImage *chartImageToPack, *chartImageToPackRotated;
  7904. if (options.padding > 0) {
  7905. chartImageToPack = &chartImagePadding;
  7906. chartImageToPackRotated = &chartImagePaddingRotated;
  7907. } else if (options.bilinear) {
  7908. chartImageToPack = &chartImageBilinear;
  7909. chartImageToPackRotated = &chartImageBilinearRotated;
  7910. } else {
  7911. chartImageToPack = &chartImage;
  7912. chartImageToPackRotated = &chartImageRotated;
  7913. }
  7914. uint32_t currentAtlas = 0;
  7915. int best_x = 0, best_y = 0;
  7916. int best_cw = 0, best_ch = 0;
  7917. int best_r = 0;
  7918. for (;;)
  7919. {
  7920. #if XA_DEBUG
  7921. bool firstChartInBitImage = false;
  7922. #endif
  7923. if (currentAtlas + 1 > m_bitImages.size()) {
  7924. // Chart doesn't fit in the current bitImage, create a new one.
  7925. BitImage *bi = XA_NEW_ARGS(MemTag::Default, BitImage, resolution, resolution);
  7926. m_bitImages.push_back(bi);
  7927. atlasSizes.push_back(Vector2i(0, 0));
  7928. #if XA_DEBUG
  7929. firstChartInBitImage = true;
  7930. #endif
  7931. if (createImage)
  7932. m_atlasImages.push_back(XA_NEW_ARGS(MemTag::Default, AtlasImage, resolution, resolution));
  7933. // Start positions are per-atlas, so create a new one of those too.
  7934. chartStartPositions.push_back(Vector2i(0, 0));
  7935. }
  7936. XA_PROFILE_START(packChartsFindLocation)
  7937. const bool foundLocation = findChartLocation(options, chartStartPositions[currentAtlas], m_bitImages[currentAtlas], chartImageToPack, chartImageToPackRotated, atlasSizes[currentAtlas].x, atlasSizes[currentAtlas].y, &best_x, &best_y, &best_cw, &best_ch, &best_r, maxResolution);
  7938. XA_PROFILE_END(packChartsFindLocation)
  7939. XA_DEBUG_ASSERT(!(firstChartInBitImage && !foundLocation)); // Chart doesn't fit in an empty, newly allocated bitImage. Shouldn't happen, since charts are resized if they are too big to fit in the atlas.
  7940. if (maxResolution == 0) {
  7941. XA_DEBUG_ASSERT(foundLocation); // The atlas isn't limited to a fixed resolution, a chart location should be found on the first attempt.
  7942. break;
  7943. }
  7944. if (foundLocation)
  7945. break;
  7946. // Chart doesn't fit in the current bitImage, try the next one.
  7947. currentAtlas++;
  7948. }
  7949. // Update brute force start location.
  7950. if (options.bruteForce) {
  7951. // Reset start location if the chart expanded the atlas.
  7952. if (best_x + best_cw > atlasSizes[currentAtlas].x || best_y + best_ch > atlasSizes[currentAtlas].y) {
  7953. for (uint32_t j = 0; j < chartStartPositions.size(); j++)
  7954. chartStartPositions[j] = Vector2i(0, 0);
  7955. }
  7956. else {
  7957. chartStartPositions[currentAtlas] = Vector2i(best_x, best_y);
  7958. }
  7959. }
  7960. // Update parametric extents.
  7961. atlasSizes[currentAtlas].x = max(atlasSizes[currentAtlas].x, best_x + best_cw);
  7962. atlasSizes[currentAtlas].y = max(atlasSizes[currentAtlas].y, best_y + best_ch);
  7963. // Resize bitImage if necessary.
  7964. // If maxResolution > 0, the bitImage is always set to maxResolutionIncludingPadding on creation and doesn't need to be dynamically resized.
  7965. if (maxResolution == 0) {
  7966. const uint32_t w = (uint32_t)atlasSizes[currentAtlas].x;
  7967. const uint32_t h = (uint32_t)atlasSizes[currentAtlas].y;
  7968. if (w > m_bitImages[0]->width() || h > m_bitImages[0]->height()) {
  7969. m_bitImages[0]->resize(nextPowerOfTwo(w), nextPowerOfTwo(h), false);
  7970. if (createImage)
  7971. m_atlasImages[0]->resize(m_bitImages[0]->width(), m_bitImages[0]->height());
  7972. }
  7973. } else {
  7974. XA_DEBUG_ASSERT(atlasSizes[currentAtlas].x <= (int)maxResolution);
  7975. XA_DEBUG_ASSERT(atlasSizes[currentAtlas].y <= (int)maxResolution);
  7976. }
  7977. XA_PROFILE_START(packChartsBlit)
  7978. addChart(m_bitImages[currentAtlas], chartImageToPack, chartImageToPackRotated, atlasSizes[currentAtlas].x, atlasSizes[currentAtlas].y, best_x, best_y, best_r);
  7979. XA_PROFILE_END(packChartsBlit)
  7980. if (createImage) {
  7981. if (best_r == 0) {
  7982. m_atlasImages[currentAtlas]->addChart(c, &chartImage, options.bilinear ? &chartImageBilinear : nullptr, options.padding > 0 ? &chartImagePadding : nullptr, atlasSizes[currentAtlas].x, atlasSizes[currentAtlas].y, best_x, best_y);
  7983. } else {
  7984. m_atlasImages[currentAtlas]->addChart(c, &chartImageRotated, options.bilinear ? &chartImageBilinearRotated : nullptr, options.padding > 0 ? &chartImagePaddingRotated : nullptr, atlasSizes[currentAtlas].x, atlasSizes[currentAtlas].y, best_x, best_y);
  7985. }
  7986. #if XA_DEBUG_EXPORT_ATLAS_IMAGES && XA_DEBUG_EXPORT_ATLAS_IMAGES_PER_CHART
  7987. for (uint32_t j = 0; j < m_atlasImages.size(); j++) {
  7988. char filename[256];
  7989. XA_SPRINTF(filename, sizeof(filename), "debug_atlas_image%02u_chart%04u.tga", j, i);
  7990. m_atlasImages[j]->writeTga(filename, (uint32_t)atlasSizes[j].x, (uint32_t)atlasSizes[j].y);
  7991. }
  7992. #endif
  7993. }
  7994. chart->atlasIndex = (int32_t)currentAtlas;
  7995. // Modify texture coordinates:
  7996. // - rotate if the chart should be rotated
  7997. // - translate to chart location
  7998. // - translate to remove padding from top and left atlas edges (unless block aligned)
  7999. for (uint32_t v = 0; v < chart->uniqueVertexCount(); v++) {
  8000. Vector2 &texcoord = chart->uniqueVertexAt(v);
  8001. Vector2 t = texcoord;
  8002. if (best_r) {
  8003. XA_DEBUG_ASSERT(options.rotateCharts);
  8004. swap(t.x, t.y);
  8005. }
  8006. texcoord.x = best_x + t.x;
  8007. texcoord.y = best_y + t.y;
  8008. texcoord.x -= (float)options.padding;
  8009. texcoord.y -= (float)options.padding;
  8010. XA_ASSERT(texcoord.x >= 0 && texcoord.y >= 0);
  8011. XA_ASSERT(isFinite(texcoord.x) && isFinite(texcoord.y));
  8012. }
  8013. if (progressFunc) {
  8014. const int newProgress = int((i + 1) / (float)chartCount * 100.0f);
  8015. if (newProgress != progress) {
  8016. progress = newProgress;
  8017. if (!progressFunc(ProgressCategory::PackCharts, progress, progressUserData))
  8018. return false;
  8019. }
  8020. }
  8021. }
  8022. // Remove padding from outer edges.
  8023. if (maxResolution == 0) {
  8024. m_width = max(0, atlasSizes[0].x - (int)options.padding * 2);
  8025. m_height = max(0, atlasSizes[0].y - (int)options.padding * 2);
  8026. } else {
  8027. m_width = m_height = maxResolution - (int)options.padding * 2;
  8028. }
  8029. XA_PRINT(" %dx%d resolution\n", m_width, m_height);
  8030. m_utilization.resize(m_bitImages.size());
  8031. for (uint32_t i = 0; i < m_utilization.size(); i++) {
  8032. if (m_width == 0 || m_height == 0)
  8033. m_utilization[i] = 0.0f;
  8034. else {
  8035. uint32_t count = 0;
  8036. for (uint32_t y = 0; y < m_height; y++) {
  8037. for (uint32_t x = 0; x < m_width; x++)
  8038. count += m_bitImages[i]->get(x, y);
  8039. }
  8040. m_utilization[i] = float(count) / (m_width * m_height);
  8041. }
  8042. if (m_utilization.size() > 1) {
  8043. XA_PRINT(" %u: %f%% utilization\n", i, m_utilization[i] * 100.0f);
  8044. }
  8045. else {
  8046. XA_PRINT(" %f%% utilization\n", m_utilization[i] * 100.0f);
  8047. }
  8048. }
  8049. #if XA_DEBUG_EXPORT_ATLAS_IMAGES
  8050. for (uint32_t i = 0; i < m_atlasImages.size(); i++) {
  8051. char filename[256];
  8052. XA_SPRINTF(filename, sizeof(filename), "debug_atlas_image%02u.tga", i);
  8053. m_atlasImages[i]->writeTga(filename, m_width, m_height);
  8054. }
  8055. #endif
  8056. if (progressFunc && progress != 100) {
  8057. if (!progressFunc(ProgressCategory::PackCharts, 100, progressUserData))
  8058. return false;
  8059. }
  8060. return true;
  8061. }
  8062. private:
  8063. bool findChartLocation(const PackOptions &options, const Vector2i &startPosition, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, uint32_t maxResolution)
  8064. {
  8065. const int attempts = 4096;
  8066. if (options.bruteForce || attempts >= w * h)
  8067. return findChartLocation_bruteForce(options, startPosition, atlasBitImage, chartBitImage, chartBitImageRotated, w, h, best_x, best_y, best_w, best_h, best_r, maxResolution);
  8068. return findChartLocation_random(options, atlasBitImage, chartBitImage, chartBitImageRotated, w, h, best_x, best_y, best_w, best_h, best_r, attempts, maxResolution);
  8069. }
  8070. bool findChartLocation_bruteForce(const PackOptions &options, const Vector2i &startPosition, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, uint32_t maxResolution)
  8071. {
  8072. const int stepSize = options.blockAlign ? 4 : 1;
  8073. int best_metric = INT_MAX;
  8074. // Try two different orientations.
  8075. for (int r = 0; r < 2; r++) {
  8076. int cw = chartBitImage->width();
  8077. int ch = chartBitImage->height();
  8078. if (r == 1) {
  8079. if (options.rotateCharts)
  8080. swap(cw, ch);
  8081. else
  8082. break;
  8083. }
  8084. for (int y = startPosition.y; y <= h + stepSize; y += stepSize) {
  8085. if (maxResolution > 0 && y > (int)maxResolution - ch)
  8086. break;
  8087. for (int x = (y == startPosition.y ? startPosition.x : 0); x <= w + stepSize; x += stepSize) {
  8088. if (maxResolution > 0 && x > (int)maxResolution - cw)
  8089. break;
  8090. // Early out if metric is not better.
  8091. const int extentX = max(w, x + cw), extentY = max(h, y + ch);
  8092. const int area = extentX * extentY;
  8093. const int extents = max(extentX, extentY);
  8094. const int metric = extents * extents + area;
  8095. if (metric > best_metric)
  8096. continue;
  8097. // If metric is the same, pick the one closest to the origin.
  8098. if (metric == best_metric && max(x, y) >= max(*best_x, *best_y))
  8099. continue;
  8100. if (!atlasBitImage->canBlit(r == 1 ? *chartBitImageRotated : *chartBitImage, x, y))
  8101. continue;
  8102. best_metric = metric;
  8103. *best_x = x;
  8104. *best_y = y;
  8105. *best_w = cw;
  8106. *best_h = ch;
  8107. *best_r = r;
  8108. if (area == w * h)
  8109. return true; // Chart is completely inside, do not look at any other location.
  8110. }
  8111. }
  8112. }
  8113. return best_metric != INT_MAX;
  8114. }
  8115. bool findChartLocation_random(const PackOptions &options, const BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int w, int h, int *best_x, int *best_y, int *best_w, int *best_h, int *best_r, int attempts, uint32_t maxResolution)
  8116. {
  8117. bool result = false;
  8118. const int BLOCK_SIZE = 4;
  8119. int best_metric = INT_MAX;
  8120. for (int i = 0; i < attempts; i++) {
  8121. int cw = chartBitImage->width();
  8122. int ch = chartBitImage->height();
  8123. int r = options.rotateCharts ? m_rand.getRange(1) : 0;
  8124. if (r == 1)
  8125. swap(cw, ch);
  8126. // + 1 to extend atlas in case atlas full. We may want to use a higher number to increase probability of extending atlas.
  8127. int xRange = w + 1;
  8128. int yRange = h + 1;
  8129. // Clamp to max resolution.
  8130. if (maxResolution > 0) {
  8131. xRange = min(xRange, (int)maxResolution - cw);
  8132. yRange = min(yRange, (int)maxResolution - ch);
  8133. }
  8134. int x = m_rand.getRange(xRange);
  8135. int y = m_rand.getRange(yRange);
  8136. if (options.blockAlign) {
  8137. x = align(x, BLOCK_SIZE);
  8138. y = align(y, BLOCK_SIZE);
  8139. if (maxResolution > 0 && (x > (int)maxResolution - cw || y > (int)maxResolution - ch))
  8140. continue; // Block alignment pushed the chart outside the atlas.
  8141. }
  8142. // Early out.
  8143. int area = max(w, x + cw) * max(h, y + ch);
  8144. //int perimeter = max(w, x+cw) + max(h, y+ch);
  8145. int extents = max(max(w, x + cw), max(h, y + ch));
  8146. int metric = extents * extents + area;
  8147. if (metric > best_metric) {
  8148. continue;
  8149. }
  8150. if (metric == best_metric && min(x, y) > min(*best_x, *best_y)) {
  8151. // If metric is the same, pick the one closest to the origin.
  8152. continue;
  8153. }
  8154. if (atlasBitImage->canBlit(r == 1 ? *chartBitImageRotated : *chartBitImage, x, y)) {
  8155. result = true;
  8156. best_metric = metric;
  8157. *best_x = x;
  8158. *best_y = y;
  8159. *best_w = cw;
  8160. *best_h = ch;
  8161. *best_r = options.rotateCharts ? r : 0;
  8162. if (area == w * h) {
  8163. // Chart is completely inside, do not look at any other location.
  8164. break;
  8165. }
  8166. }
  8167. }
  8168. return result;
  8169. }
  8170. void addChart(BitImage *atlasBitImage, const BitImage *chartBitImage, const BitImage *chartBitImageRotated, int atlas_w, int atlas_h, int offset_x, int offset_y, int r)
  8171. {
  8172. XA_DEBUG_ASSERT(r == 0 || r == 1);
  8173. const BitImage *image = r == 0 ? chartBitImage : chartBitImageRotated;
  8174. const int w = image->width();
  8175. const int h = image->height();
  8176. for (int y = 0; y < h; y++) {
  8177. int yy = y + offset_y;
  8178. if (yy >= 0) {
  8179. for (int x = 0; x < w; x++) {
  8180. int xx = x + offset_x;
  8181. if (xx >= 0) {
  8182. if (image->get(x, y)) {
  8183. if (xx < atlas_w && yy < atlas_h) {
  8184. XA_DEBUG_ASSERT(atlasBitImage->get(xx, yy) == false);
  8185. atlasBitImage->set(xx, yy);
  8186. }
  8187. }
  8188. }
  8189. }
  8190. }
  8191. }
  8192. }
  8193. void bilinearExpand(const Chart *chart, BitImage *source, BitImage *dest, BitImage *destRotated, UniformGrid2 &boundaryEdgeGrid) const
  8194. {
  8195. boundaryEdgeGrid.reset(chart->vertices, chart->indices);
  8196. if (chart->boundaryEdges) {
  8197. const uint32_t edgeCount = chart->boundaryEdges->size();
  8198. for (uint32_t i = 0; i < edgeCount; i++)
  8199. boundaryEdgeGrid.append((*chart->boundaryEdges)[i]);
  8200. } else {
  8201. for (uint32_t i = 0; i < chart->indices.length; i++)
  8202. boundaryEdgeGrid.append(i);
  8203. }
  8204. const int xOffsets[] = { -1, 0, 1, -1, 1, -1, 0, 1 };
  8205. const int yOffsets[] = { -1, -1, -1, 0, 0, 1, 1, 1 };
  8206. for (uint32_t y = 0; y < source->height(); y++) {
  8207. for (uint32_t x = 0; x < source->width(); x++) {
  8208. // Copy pixels from source.
  8209. if (source->get(x, y))
  8210. goto setPixel;
  8211. // Empty pixel. If none of of the surrounding pixels are set, this pixel can't be sampled by bilinear interpolation.
  8212. {
  8213. uint32_t s = 0;
  8214. for (; s < 8; s++) {
  8215. const int sx = (int)x + xOffsets[s];
  8216. const int sy = (int)y + yOffsets[s];
  8217. if (sx < 0 || sy < 0 || sx >= (int)source->width() || sy >= (int)source->height())
  8218. continue;
  8219. if (source->get((uint32_t)sx, (uint32_t)sy))
  8220. break;
  8221. }
  8222. if (s == 8)
  8223. continue;
  8224. }
  8225. {
  8226. // If a 2x2 square centered on the pixels centroid intersects the triangle, this pixel will be sampled by bilinear interpolation.
  8227. // See "Precomputed Global Illumination in Frostbite (GDC 2018)" page 95
  8228. const Vector2 centroid((float)x + 0.5f, (float)y + 0.5f);
  8229. const Vector2 squareVertices[4] = {
  8230. Vector2(centroid.x - 1.0f, centroid.y - 1.0f),
  8231. Vector2(centroid.x + 1.0f, centroid.y - 1.0f),
  8232. Vector2(centroid.x + 1.0f, centroid.y + 1.0f),
  8233. Vector2(centroid.x - 1.0f, centroid.y + 1.0f)
  8234. };
  8235. for (uint32_t j = 0; j < 4; j++) {
  8236. if (boundaryEdgeGrid.intersect(squareVertices[j], squareVertices[(j + 1) % 4], 0.0f))
  8237. goto setPixel;
  8238. }
  8239. }
  8240. continue;
  8241. setPixel:
  8242. dest->set(x, y);
  8243. if (destRotated)
  8244. destRotated->set(y, x);
  8245. }
  8246. }
  8247. }
  8248. struct DrawTriangleCallbackArgs
  8249. {
  8250. BitImage *chartBitImage, *chartBitImageRotated;
  8251. };
  8252. static bool drawTriangleCallback(void *param, int x, int y)
  8253. {
  8254. auto args = (DrawTriangleCallbackArgs *)param;
  8255. args->chartBitImage->set(x, y);
  8256. if (args->chartBitImageRotated)
  8257. args->chartBitImageRotated->set(y, x);
  8258. return true;
  8259. }
  8260. Array<AtlasImage *> m_atlasImages;
  8261. Array<float> m_utilization;
  8262. Array<BitImage *> m_bitImages;
  8263. Array<Chart *> m_charts;
  8264. RadixSort m_radix;
  8265. uint32_t m_width = 0;
  8266. uint32_t m_height = 0;
  8267. float m_texelsPerUnit = 0.0f;
  8268. KISSRng m_rand;
  8269. };
  8270. } // namespace pack
  8271. } // namespace internal
  8272. // Used to map triangulated polygons back to polygons.
  8273. struct MeshPolygonMapping
  8274. {
  8275. internal::Array<uint8_t> faceVertexCount; // Copied from MeshDecl::faceVertexCount.
  8276. internal::Array<uint32_t> triangleToPolygonMap; // Triangle index (mesh face index) to polygon index.
  8277. internal::Array<uint32_t> triangleToPolygonIndicesMap; // Triangle indices to polygon indices.
  8278. };
  8279. struct Context
  8280. {
  8281. Atlas atlas;
  8282. internal::Progress *addMeshProgress = nullptr;
  8283. internal::TaskGroupHandle addMeshTaskGroup;
  8284. internal::param::Atlas paramAtlas;
  8285. ProgressFunc progressFunc = nullptr;
  8286. void *progressUserData = nullptr;
  8287. internal::TaskScheduler *taskScheduler;
  8288. internal::Array<internal::Mesh *> meshes;
  8289. internal::Array<MeshPolygonMapping *> meshPolygonMappings;
  8290. internal::Array<internal::UvMesh *> uvMeshes;
  8291. internal::Array<internal::UvMeshInstance *> uvMeshInstances;
  8292. bool uvMeshChartsComputed = false;
  8293. };
  8294. Atlas *Create()
  8295. {
  8296. Context *ctx = XA_NEW(internal::MemTag::Default, Context);
  8297. memset(&ctx->atlas, 0, sizeof(Atlas));
  8298. ctx->taskScheduler = XA_NEW(internal::MemTag::Default, internal::TaskScheduler);
  8299. return &ctx->atlas;
  8300. }
  8301. static void DestroyOutputMeshes(Context *ctx)
  8302. {
  8303. if (!ctx->atlas.meshes)
  8304. return;
  8305. for (int i = 0; i < (int)ctx->atlas.meshCount; i++) {
  8306. Mesh &mesh = ctx->atlas.meshes[i];
  8307. if (mesh.chartArray) {
  8308. for (uint32_t j = 0; j < mesh.chartCount; j++) {
  8309. if (mesh.chartArray[j].faceArray)
  8310. XA_FREE(mesh.chartArray[j].faceArray);
  8311. }
  8312. XA_FREE(mesh.chartArray);
  8313. }
  8314. if (mesh.vertexArray)
  8315. XA_FREE(mesh.vertexArray);
  8316. if (mesh.indexArray)
  8317. XA_FREE(mesh.indexArray);
  8318. }
  8319. XA_FREE(ctx->atlas.meshes);
  8320. ctx->atlas.meshes = nullptr;
  8321. }
  8322. void Destroy(Atlas *atlas)
  8323. {
  8324. XA_DEBUG_ASSERT(atlas);
  8325. Context *ctx = (Context *)atlas;
  8326. if (atlas->utilization)
  8327. XA_FREE(atlas->utilization);
  8328. if (atlas->image)
  8329. XA_FREE(atlas->image);
  8330. DestroyOutputMeshes(ctx);
  8331. if (ctx->addMeshProgress) {
  8332. ctx->addMeshProgress->cancel = true;
  8333. AddMeshJoin(atlas); // frees addMeshProgress
  8334. }
  8335. ctx->taskScheduler->~TaskScheduler();
  8336. XA_FREE(ctx->taskScheduler);
  8337. for (uint32_t i = 0; i < ctx->meshes.size(); i++) {
  8338. internal::Mesh *mesh = ctx->meshes[i];
  8339. mesh->~Mesh();
  8340. XA_FREE(mesh);
  8341. }
  8342. for (uint32_t i = 0; i < ctx->meshPolygonMappings.size(); i++) {
  8343. MeshPolygonMapping *mapping = ctx->meshPolygonMappings[i];
  8344. if (mapping) {
  8345. mapping->~MeshPolygonMapping();
  8346. XA_FREE(mapping);
  8347. }
  8348. }
  8349. for (uint32_t i = 0; i < ctx->uvMeshes.size(); i++) {
  8350. internal::UvMesh *mesh = ctx->uvMeshes[i];
  8351. for (uint32_t j = 0; j < mesh->charts.size(); j++) {
  8352. mesh->charts[j]->~UvMeshChart();
  8353. XA_FREE(mesh->charts[j]);
  8354. }
  8355. mesh->~UvMesh();
  8356. XA_FREE(mesh);
  8357. }
  8358. for (uint32_t i = 0; i < ctx->uvMeshInstances.size(); i++) {
  8359. internal::UvMeshInstance *mesh = ctx->uvMeshInstances[i];
  8360. mesh->~UvMeshInstance();
  8361. XA_FREE(mesh);
  8362. }
  8363. ctx->~Context();
  8364. XA_FREE(ctx);
  8365. #if XA_DEBUG_HEAP
  8366. internal::ReportLeaks();
  8367. #endif
  8368. }
  8369. static void runAddMeshTask(void *groupUserData, void *taskUserData)
  8370. {
  8371. XA_PROFILE_START(addMeshThread)
  8372. auto ctx = (Context *)groupUserData;
  8373. auto mesh = (internal::Mesh *)taskUserData;
  8374. internal::Progress *progress = ctx->addMeshProgress;
  8375. if (progress->cancel) {
  8376. XA_PROFILE_END(addMeshThread)
  8377. return;
  8378. }
  8379. XA_PROFILE_START(addMeshCreateColocals)
  8380. mesh->createColocals();
  8381. XA_PROFILE_END(addMeshCreateColocals)
  8382. if (progress->cancel) {
  8383. XA_PROFILE_END(addMeshThread)
  8384. return;
  8385. }
  8386. progress->increment(1);
  8387. XA_PROFILE_END(addMeshThread)
  8388. }
  8389. static internal::Vector3 DecodePosition(const MeshDecl &meshDecl, uint32_t index)
  8390. {
  8391. XA_DEBUG_ASSERT(meshDecl.vertexPositionData);
  8392. XA_DEBUG_ASSERT(meshDecl.vertexPositionStride > 0);
  8393. return *((const internal::Vector3 *)&((const uint8_t *)meshDecl.vertexPositionData)[meshDecl.vertexPositionStride * index]);
  8394. }
  8395. static internal::Vector3 DecodeNormal(const MeshDecl &meshDecl, uint32_t index)
  8396. {
  8397. XA_DEBUG_ASSERT(meshDecl.vertexNormalData);
  8398. XA_DEBUG_ASSERT(meshDecl.vertexNormalStride > 0);
  8399. return *((const internal::Vector3 *)&((const uint8_t *)meshDecl.vertexNormalData)[meshDecl.vertexNormalStride * index]);
  8400. }
  8401. static internal::Vector2 DecodeUv(const MeshDecl &meshDecl, uint32_t index)
  8402. {
  8403. XA_DEBUG_ASSERT(meshDecl.vertexUvData);
  8404. XA_DEBUG_ASSERT(meshDecl.vertexUvStride > 0);
  8405. return *((const internal::Vector2 *)&((const uint8_t *)meshDecl.vertexUvData)[meshDecl.vertexUvStride * index]);
  8406. }
  8407. static uint32_t DecodeIndex(IndexFormat format, const void *indexData, int32_t offset, uint32_t i)
  8408. {
  8409. XA_DEBUG_ASSERT(indexData);
  8410. if (format == IndexFormat::UInt16)
  8411. return uint16_t((int32_t)((const uint16_t *)indexData)[i] + offset);
  8412. return uint32_t((int32_t)((const uint32_t *)indexData)[i] + offset);
  8413. }
  8414. AddMeshError AddMesh(Atlas *atlas, const MeshDecl &meshDecl, uint32_t meshCountHint)
  8415. {
  8416. XA_DEBUG_ASSERT(atlas);
  8417. if (!atlas) {
  8418. XA_PRINT_WARNING("AddMesh: atlas is null.\n");
  8419. return AddMeshError::Error;
  8420. }
  8421. Context *ctx = (Context *)atlas;
  8422. if (!ctx->uvMeshes.isEmpty()) {
  8423. XA_PRINT_WARNING("AddMesh: Meshes and UV meshes cannot be added to the same atlas.\n");
  8424. return AddMeshError::Error;
  8425. }
  8426. #if XA_PROFILE
  8427. if (ctx->meshes.isEmpty())
  8428. internal::s_profile.addMeshRealStart = std::chrono::high_resolution_clock::now();
  8429. #endif
  8430. // Don't know how many times AddMesh will be called, so progress needs to adjusted each time.
  8431. if (!ctx->addMeshProgress) {
  8432. ctx->addMeshProgress = XA_NEW_ARGS(internal::MemTag::Default, internal::Progress, ProgressCategory::AddMesh, ctx->progressFunc, ctx->progressUserData, 1);
  8433. }
  8434. else {
  8435. ctx->addMeshProgress->setMaxValue(internal::max(ctx->meshes.size() + 1, meshCountHint));
  8436. }
  8437. XA_PROFILE_START(addMeshCopyData)
  8438. const bool hasIndices = meshDecl.indexCount > 0;
  8439. const uint32_t indexCount = hasIndices ? meshDecl.indexCount : meshDecl.vertexCount;
  8440. uint32_t faceCount = indexCount / 3;
  8441. if (meshDecl.faceVertexCount) {
  8442. faceCount = meshDecl.faceCount;
  8443. XA_PRINT("Adding mesh %d: %u vertices, %u polygons\n", ctx->meshes.size(), meshDecl.vertexCount, faceCount);
  8444. for (uint32_t f = 0; f < faceCount; f++) {
  8445. if (meshDecl.faceVertexCount[f] < 3)
  8446. return AddMeshError::InvalidFaceVertexCount;
  8447. }
  8448. } else {
  8449. XA_PRINT("Adding mesh %d: %u vertices, %u triangles\n", ctx->meshes.size(), meshDecl.vertexCount, faceCount);
  8450. // Expecting triangle faces unless otherwise specified.
  8451. if ((indexCount % 3) != 0)
  8452. return AddMeshError::InvalidIndexCount;
  8453. }
  8454. uint32_t meshFlags = internal::MeshFlags::HasIgnoredFaces;
  8455. if (meshDecl.vertexNormalData)
  8456. meshFlags |= internal::MeshFlags::HasNormals;
  8457. if (meshDecl.faceMaterialData)
  8458. meshFlags |= internal::MeshFlags::HasMaterials;
  8459. internal::Mesh *mesh = XA_NEW_ARGS(internal::MemTag::Mesh, internal::Mesh, meshDecl.epsilon, meshDecl.vertexCount, indexCount / 3, meshFlags, ctx->meshes.size());
  8460. for (uint32_t i = 0; i < meshDecl.vertexCount; i++) {
  8461. internal::Vector3 normal(0.0f);
  8462. internal::Vector2 texcoord(0.0f);
  8463. if (meshDecl.vertexNormalData)
  8464. normal = DecodeNormal(meshDecl, i);
  8465. if (meshDecl.vertexUvData)
  8466. texcoord = DecodeUv(meshDecl, i);
  8467. mesh->addVertex(DecodePosition(meshDecl, i), normal, texcoord);
  8468. }
  8469. MeshPolygonMapping *meshPolygonMapping = nullptr;
  8470. if (meshDecl.faceVertexCount) {
  8471. meshPolygonMapping = XA_NEW(internal::MemTag::Default, MeshPolygonMapping);
  8472. // Copy MeshDecl::faceVertexCount so it can be used later when building output meshes.
  8473. meshPolygonMapping->faceVertexCount.copyFrom(meshDecl.faceVertexCount, meshDecl.faceCount);
  8474. // There should be at least as many triangles as polygons.
  8475. meshPolygonMapping->triangleToPolygonMap.reserve(meshDecl.faceCount);
  8476. meshPolygonMapping->triangleToPolygonIndicesMap.reserve(meshDecl.indexCount);
  8477. }
  8478. const uint32_t kMaxWarnings = 50;
  8479. uint32_t warningCount = 0;
  8480. internal::Array<uint32_t> triIndices;
  8481. internal::Triangulator triangulator;
  8482. for (uint32_t face = 0; face < faceCount; face++) {
  8483. // Decode face indices.
  8484. const uint32_t faceVertexCount = meshDecl.faceVertexCount ? (uint32_t)meshDecl.faceVertexCount[face] : 3;
  8485. uint32_t polygon[UINT8_MAX];
  8486. for (uint32_t i = 0; i < faceVertexCount; i++) {
  8487. if (hasIndices) {
  8488. polygon[i] = DecodeIndex(meshDecl.indexFormat, meshDecl.indexData, meshDecl.indexOffset, face * faceVertexCount + i);
  8489. // Check if any index is out of range.
  8490. if (polygon[i] >= meshDecl.vertexCount) {
  8491. mesh->~Mesh();
  8492. XA_FREE(mesh);
  8493. return AddMeshError::IndexOutOfRange;
  8494. }
  8495. } else {
  8496. polygon[i] = face * faceVertexCount + i;
  8497. }
  8498. }
  8499. // Ignore faces with degenerate or zero length edges.
  8500. bool ignore = false;
  8501. for (uint32_t i = 0; i < faceVertexCount; i++) {
  8502. const uint32_t index1 = polygon[i];
  8503. const uint32_t index2 = polygon[(i + 1) % 3];
  8504. if (index1 == index2) {
  8505. ignore = true;
  8506. if (++warningCount <= kMaxWarnings)
  8507. XA_PRINT(" Degenerate edge: index %d, index %d\n", index1, index2);
  8508. break;
  8509. }
  8510. const internal::Vector3 &pos1 = mesh->position(index1);
  8511. const internal::Vector3 &pos2 = mesh->position(index2);
  8512. if (internal::length(pos2 - pos1) <= 0.0f) {
  8513. ignore = true;
  8514. if (++warningCount <= kMaxWarnings)
  8515. XA_PRINT(" Zero length edge: index %d position (%g %g %g), index %d position (%g %g %g)\n", index1, pos1.x, pos1.y, pos1.z, index2, pos2.x, pos2.y, pos2.z);
  8516. break;
  8517. }
  8518. }
  8519. // Ignore faces with any nan vertex attributes.
  8520. if (!ignore) {
  8521. for (uint32_t i = 0; i < faceVertexCount; i++) {
  8522. const internal::Vector3 &pos = mesh->position(polygon[i]);
  8523. if (internal::isNan(pos.x) || internal::isNan(pos.y) || internal::isNan(pos.z)) {
  8524. if (++warningCount <= kMaxWarnings)
  8525. XA_PRINT(" NAN position in face: %d\n", face);
  8526. ignore = true;
  8527. break;
  8528. }
  8529. if (meshDecl.vertexNormalData) {
  8530. const internal::Vector3 &normal = mesh->normal(polygon[i]);
  8531. if (internal::isNan(normal.x) || internal::isNan(normal.y) || internal::isNan(normal.z)) {
  8532. if (++warningCount <= kMaxWarnings)
  8533. XA_PRINT(" NAN normal in face: %d\n", face);
  8534. ignore = true;
  8535. break;
  8536. }
  8537. }
  8538. if (meshDecl.vertexUvData) {
  8539. const internal::Vector2 &uv = mesh->texcoord(polygon[i]);
  8540. if (internal::isNan(uv.x) || internal::isNan(uv.y)) {
  8541. if (++warningCount <= kMaxWarnings)
  8542. XA_PRINT(" NAN texture coordinate in face: %d\n", face);
  8543. ignore = true;
  8544. break;
  8545. }
  8546. }
  8547. }
  8548. }
  8549. // Triangulate if necessary.
  8550. triIndices.clear();
  8551. if (faceVertexCount == 3) {
  8552. triIndices.push_back(polygon[0]);
  8553. triIndices.push_back(polygon[1]);
  8554. triIndices.push_back(polygon[2]);
  8555. } else {
  8556. triangulator.triangulatePolygon(mesh->positions(), internal::ConstArrayView<uint32_t>(polygon, faceVertexCount), triIndices);
  8557. }
  8558. // Check for zero area faces.
  8559. if (!ignore) {
  8560. for (uint32_t i = 0; i < triIndices.size(); i += 3) {
  8561. const internal::Vector3 &a = mesh->position(triIndices[i + 0]);
  8562. const internal::Vector3 &b = mesh->position(triIndices[i + 1]);
  8563. const internal::Vector3 &c = mesh->position(triIndices[i + 2]);
  8564. const float area = internal::length(internal::cross(b - a, c - a)) * 0.5f;
  8565. if (area <= internal::kAreaEpsilon) {
  8566. ignore = true;
  8567. if (++warningCount <= kMaxWarnings)
  8568. XA_PRINT(" Zero area face: %d, area is %f\n", face, area);
  8569. break;
  8570. }
  8571. }
  8572. }
  8573. // User face ignore.
  8574. if (meshDecl.faceIgnoreData && meshDecl.faceIgnoreData[face])
  8575. ignore = true;
  8576. // User material.
  8577. uint32_t material = UINT32_MAX;
  8578. if (meshDecl.faceMaterialData)
  8579. material = meshDecl.faceMaterialData[face];
  8580. // Add the face(s).
  8581. for (uint32_t i = 0; i < triIndices.size(); i += 3) {
  8582. mesh->addFace(&triIndices[i], ignore, material);
  8583. if (meshPolygonMapping)
  8584. meshPolygonMapping->triangleToPolygonMap.push_back(face);
  8585. }
  8586. if (meshPolygonMapping) {
  8587. for (uint32_t i = 0; i < triIndices.size(); i++)
  8588. meshPolygonMapping->triangleToPolygonIndicesMap.push_back(triIndices[i]);
  8589. }
  8590. }
  8591. if (warningCount > kMaxWarnings)
  8592. XA_PRINT(" %u additional warnings truncated\n", warningCount - kMaxWarnings);
  8593. XA_PROFILE_END(addMeshCopyData)
  8594. ctx->meshes.push_back(mesh);
  8595. ctx->meshPolygonMappings.push_back(meshPolygonMapping);
  8596. ctx->paramAtlas.addMesh(mesh);
  8597. if (ctx->addMeshTaskGroup.value == UINT32_MAX)
  8598. ctx->addMeshTaskGroup = ctx->taskScheduler->createTaskGroup(ctx);
  8599. internal::Task task;
  8600. task.userData = mesh;
  8601. task.func = runAddMeshTask;
  8602. ctx->taskScheduler->run(ctx->addMeshTaskGroup, task);
  8603. return AddMeshError::Success;
  8604. }
  8605. void AddMeshJoin(Atlas *atlas)
  8606. {
  8607. XA_DEBUG_ASSERT(atlas);
  8608. if (!atlas) {
  8609. XA_PRINT_WARNING("AddMeshJoin: atlas is null.\n");
  8610. return;
  8611. }
  8612. Context *ctx = (Context *)atlas;
  8613. if (!ctx->uvMeshes.isEmpty()) {
  8614. #if XA_PROFILE
  8615. XA_PRINT("Added %u UV meshes\n", ctx->uvMeshes.size());
  8616. internal::s_profile.addMeshReal = uint64_t(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - internal::s_profile.addMeshRealStart).count());
  8617. #endif
  8618. XA_PROFILE_PRINT_AND_RESET(" Total: ", addMeshReal)
  8619. XA_PROFILE_PRINT_AND_RESET(" Copy data: ", addMeshCopyData)
  8620. #if XA_PROFILE_ALLOC
  8621. XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
  8622. #endif
  8623. XA_PRINT_MEM_USAGE
  8624. } else {
  8625. if (!ctx->addMeshProgress)
  8626. return;
  8627. ctx->taskScheduler->wait(&ctx->addMeshTaskGroup);
  8628. ctx->addMeshProgress->~Progress();
  8629. XA_FREE(ctx->addMeshProgress);
  8630. ctx->addMeshProgress = nullptr;
  8631. #if XA_PROFILE
  8632. XA_PRINT("Added %u meshes\n", ctx->meshes.size());
  8633. internal::s_profile.addMeshReal = uint64_t(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - internal::s_profile.addMeshRealStart).count());
  8634. #endif
  8635. XA_PROFILE_PRINT_AND_RESET(" Total (real): ", addMeshReal)
  8636. XA_PROFILE_PRINT_AND_RESET(" Copy data: ", addMeshCopyData)
  8637. XA_PROFILE_PRINT_AND_RESET(" Total (thread): ", addMeshThread)
  8638. XA_PROFILE_PRINT_AND_RESET(" Create colocals: ", addMeshCreateColocals)
  8639. #if XA_PROFILE_ALLOC
  8640. XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
  8641. #endif
  8642. XA_PRINT_MEM_USAGE
  8643. #if XA_DEBUG_EXPORT_OBJ_FACE_GROUPS
  8644. internal::param::s_faceGroupsCurrentVertex = 0;
  8645. #endif
  8646. }
  8647. }
  8648. AddMeshError AddUvMesh(Atlas *atlas, const UvMeshDecl &decl)
  8649. {
  8650. XA_DEBUG_ASSERT(atlas);
  8651. if (!atlas) {
  8652. XA_PRINT_WARNING("AddUvMesh: atlas is null.\n");
  8653. return AddMeshError::Error;
  8654. }
  8655. Context *ctx = (Context *)atlas;
  8656. if (!ctx->meshes.isEmpty()) {
  8657. XA_PRINT_WARNING("AddUvMesh: Meshes and UV meshes cannot be added to the same atlas.\n");
  8658. return AddMeshError::Error;
  8659. }
  8660. #if XA_PROFILE
  8661. if (ctx->uvMeshInstances.isEmpty())
  8662. internal::s_profile.addMeshRealStart = std::chrono::high_resolution_clock::now();
  8663. #endif
  8664. XA_PROFILE_START(addMeshCopyData)
  8665. const bool hasIndices = decl.indexCount > 0;
  8666. const uint32_t indexCount = hasIndices ? decl.indexCount : decl.vertexCount;
  8667. XA_PRINT("Adding UV mesh %d: %u vertices, %u triangles\n", ctx->uvMeshes.size(), decl.vertexCount, indexCount / 3);
  8668. // Expecting triangle faces.
  8669. if ((indexCount % 3) != 0)
  8670. return AddMeshError::InvalidIndexCount;
  8671. if (hasIndices) {
  8672. // Check if any index is out of range.
  8673. for (uint32_t i = 0; i < indexCount; i++) {
  8674. const uint32_t index = DecodeIndex(decl.indexFormat, decl.indexData, decl.indexOffset, i);
  8675. if (index >= decl.vertexCount)
  8676. return AddMeshError::IndexOutOfRange;
  8677. }
  8678. }
  8679. // Create a mesh instance.
  8680. internal::UvMeshInstance *meshInstance = XA_NEW(internal::MemTag::Default, internal::UvMeshInstance);
  8681. meshInstance->mesh = nullptr;
  8682. ctx->uvMeshInstances.push_back(meshInstance);
  8683. // See if this is an instance of an already existing mesh.
  8684. internal::UvMesh *mesh = nullptr;
  8685. for (uint32_t m = 0; m < ctx->uvMeshes.size(); m++) {
  8686. if (memcmp(&ctx->uvMeshes[m]->decl, &decl, sizeof(UvMeshDecl)) == 0) {
  8687. mesh = ctx->uvMeshes[m];
  8688. XA_PRINT(" instance of a previous UV mesh\n");
  8689. break;
  8690. }
  8691. }
  8692. if (!mesh) {
  8693. // Copy geometry to mesh.
  8694. mesh = XA_NEW(internal::MemTag::Default, internal::UvMesh);
  8695. ctx->uvMeshes.push_back(mesh);
  8696. mesh->decl = decl;
  8697. if (decl.faceMaterialData) {
  8698. mesh->faceMaterials.resize(decl.indexCount / 3);
  8699. memcpy(mesh->faceMaterials.data(), decl.faceMaterialData, mesh->faceMaterials.size() * sizeof(uint32_t));
  8700. }
  8701. mesh->indices.resize(decl.indexCount);
  8702. for (uint32_t i = 0; i < indexCount; i++)
  8703. mesh->indices[i] = hasIndices ? DecodeIndex(decl.indexFormat, decl.indexData, decl.indexOffset, i) : i;
  8704. mesh->texcoords.resize(decl.vertexCount);
  8705. for (uint32_t i = 0; i < decl.vertexCount; i++)
  8706. mesh->texcoords[i] = *((const internal::Vector2 *)&((const uint8_t *)decl.vertexUvData)[decl.vertexStride * i]);
  8707. // Validate.
  8708. mesh->faceIgnore.resize(decl.indexCount / 3);
  8709. mesh->faceIgnore.zeroOutMemory();
  8710. const uint32_t kMaxWarnings = 50;
  8711. uint32_t warningCount = 0;
  8712. for (uint32_t f = 0; f < indexCount / 3; f++) {
  8713. bool ignore = false;
  8714. uint32_t tri[3];
  8715. for (uint32_t i = 0; i < 3; i++)
  8716. tri[i] = mesh->indices[f * 3 + i];
  8717. // Check for nan UVs.
  8718. for (uint32_t i = 0; i < 3; i++) {
  8719. const uint32_t vertex = tri[i];
  8720. if (internal::isNan(mesh->texcoords[vertex].x) || internal::isNan(mesh->texcoords[vertex].y)) {
  8721. ignore = true;
  8722. if (++warningCount <= kMaxWarnings)
  8723. XA_PRINT(" NAN texture coordinate in vertex %u\n", vertex);
  8724. break;
  8725. }
  8726. }
  8727. // Check for zero area faces.
  8728. if (!ignore) {
  8729. const internal::Vector2 &v1 = mesh->texcoords[tri[0]];
  8730. const internal::Vector2 &v2 = mesh->texcoords[tri[1]];
  8731. const internal::Vector2 &v3 = mesh->texcoords[tri[2]];
  8732. const float area = fabsf(((v2.x - v1.x) * (v3.y - v1.y) - (v3.x - v1.x) * (v2.y - v1.y)) * 0.5f);
  8733. if (area <= internal::kAreaEpsilon) {
  8734. ignore = true;
  8735. if (++warningCount <= kMaxWarnings)
  8736. XA_PRINT(" Zero area face: %d, indices (%d %d %d), area is %f\n", f, tri[0], tri[1], tri[2], area);
  8737. }
  8738. }
  8739. if (ignore)
  8740. mesh->faceIgnore.set(f);
  8741. }
  8742. if (warningCount > kMaxWarnings)
  8743. XA_PRINT(" %u additional warnings truncated\n", warningCount - kMaxWarnings);
  8744. }
  8745. meshInstance->mesh = mesh;
  8746. XA_PROFILE_END(addMeshCopyData)
  8747. return AddMeshError::Success;
  8748. }
  8749. void ComputeCharts(Atlas *atlas, ChartOptions options)
  8750. {
  8751. if (!atlas) {
  8752. XA_PRINT_WARNING("ComputeCharts: atlas is null.\n");
  8753. return;
  8754. }
  8755. Context *ctx = (Context *)atlas;
  8756. AddMeshJoin(atlas);
  8757. if (ctx->meshes.isEmpty() && ctx->uvMeshInstances.isEmpty()) {
  8758. XA_PRINT_WARNING("ComputeCharts: No meshes. Call AddMesh or AddUvMesh first.\n");
  8759. return;
  8760. }
  8761. // Reset atlas state. This function may be called multiple times, or again after PackCharts.
  8762. if (atlas->utilization)
  8763. XA_FREE(atlas->utilization);
  8764. if (atlas->image)
  8765. XA_FREE(atlas->image);
  8766. DestroyOutputMeshes(ctx);
  8767. memset(&ctx->atlas, 0, sizeof(Atlas));
  8768. XA_PRINT("Computing charts\n");
  8769. if (!ctx->meshes.isEmpty()) {
  8770. if (!ctx->paramAtlas.computeCharts(ctx->taskScheduler, options, ctx->progressFunc, ctx->progressUserData)) {
  8771. XA_PRINT(" Cancelled by user\n");
  8772. return;
  8773. }
  8774. uint32_t chartsWithTJunctionsCount = 0, tJunctionCount = 0, orthoChartsCount = 0, planarChartsCount = 0, lscmChartsCount = 0, piecewiseChartsCount = 0, originalUvChartsCount = 0;
  8775. uint32_t chartCount = 0;
  8776. const uint32_t meshCount = ctx->meshes.size();
  8777. for (uint32_t i = 0; i < meshCount; i++) {
  8778. for (uint32_t j = 0; j < ctx->paramAtlas.chartGroupCount(i); j++) {
  8779. const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, j);
  8780. for (uint32_t k = 0; k < chartGroup->chartCount(); k++) {
  8781. const internal::param::Chart *chart = chartGroup->chartAt(k);
  8782. tJunctionCount += chart->tjunctionCount();
  8783. if (chart->tjunctionCount() > 0)
  8784. chartsWithTJunctionsCount++;
  8785. if (chart->type() == ChartType::Planar)
  8786. planarChartsCount++;
  8787. else if (chart->type() == ChartType::Ortho)
  8788. orthoChartsCount++;
  8789. else if (chart->type() == ChartType::LSCM)
  8790. lscmChartsCount++;
  8791. else if (chart->type() == ChartType::Piecewise)
  8792. piecewiseChartsCount++;
  8793. if (chart->generatorType() == internal::segment::ChartGeneratorType::OriginalUv)
  8794. originalUvChartsCount++;
  8795. }
  8796. chartCount += chartGroup->chartCount();
  8797. }
  8798. }
  8799. if (tJunctionCount > 0)
  8800. XA_PRINT(" %u t-junctions found in %u charts\n", tJunctionCount, chartsWithTJunctionsCount);
  8801. XA_PRINT(" %u charts\n", chartCount);
  8802. XA_PRINT(" %u planar, %u ortho, %u LSCM, %u piecewise\n", planarChartsCount, orthoChartsCount, lscmChartsCount, piecewiseChartsCount);
  8803. if (originalUvChartsCount > 0)
  8804. XA_PRINT(" %u with original UVs\n", originalUvChartsCount);
  8805. uint32_t chartIndex = 0, invalidParamCount = 0;
  8806. for (uint32_t i = 0; i < meshCount; i++) {
  8807. for (uint32_t j = 0; j < ctx->paramAtlas.chartGroupCount(i); j++) {
  8808. const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, j);
  8809. for (uint32_t k = 0; k < chartGroup->chartCount(); k++) {
  8810. internal::param::Chart *chart = chartGroup->chartAt(k);
  8811. const internal::param::Quality &quality = chart->quality();
  8812. #if XA_DEBUG_EXPORT_OBJ_CHARTS_AFTER_PARAMETERIZATION
  8813. {
  8814. char filename[256];
  8815. XA_SPRINTF(filename, sizeof(filename), "debug_chart_%03u_after_parameterization.obj", chartIndex);
  8816. chart->unifiedMesh()->writeObjFile(filename);
  8817. }
  8818. #endif
  8819. const char *type = "LSCM";
  8820. if (chart->type() == ChartType::Planar)
  8821. type = "planar";
  8822. else if (chart->type() == ChartType::Ortho)
  8823. type = "ortho";
  8824. else if (chart->type() == ChartType::Piecewise)
  8825. type = "piecewise";
  8826. if (chart->isInvalid()) {
  8827. if (quality.boundaryIntersection) {
  8828. XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, self-intersecting boundary.\n", chartIndex, i, j, k, type);
  8829. }
  8830. if (quality.flippedTriangleCount > 0) {
  8831. XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, %u / %u flipped triangles.\n", chartIndex, i, j, k, type, quality.flippedTriangleCount, quality.totalTriangleCount);
  8832. }
  8833. if (quality.zeroAreaTriangleCount > 0) {
  8834. XA_PRINT_WARNING(" Chart %u (mesh %u, group %u, id %u) (%s): invalid parameterization, %u / %u zero area triangles.\n", chartIndex, i, j, k, type, quality.zeroAreaTriangleCount, quality.totalTriangleCount);
  8835. }
  8836. invalidParamCount++;
  8837. #if XA_DEBUG_EXPORT_OBJ_INVALID_PARAMETERIZATION
  8838. char filename[256];
  8839. XA_SPRINTF(filename, sizeof(filename), "debug_chart_%03u_invalid_parameterization.obj", chartIndex);
  8840. const internal::Mesh *mesh = chart->unifiedMesh();
  8841. FILE *file;
  8842. XA_FOPEN(file, filename, "w");
  8843. if (file) {
  8844. mesh->writeObjVertices(file);
  8845. fprintf(file, "s off\n");
  8846. fprintf(file, "o object\n");
  8847. for (uint32_t f = 0; f < mesh->faceCount(); f++)
  8848. mesh->writeObjFace(file, f);
  8849. if (!chart->paramFlippedFaces().isEmpty()) {
  8850. fprintf(file, "o flipped_faces\n");
  8851. for (uint32_t f = 0; f < chart->paramFlippedFaces().size(); f++)
  8852. mesh->writeObjFace(file, chart->paramFlippedFaces()[f]);
  8853. }
  8854. mesh->writeObjBoundaryEges(file);
  8855. fclose(file);
  8856. }
  8857. #endif
  8858. }
  8859. chartIndex++;
  8860. }
  8861. }
  8862. }
  8863. if (invalidParamCount > 0)
  8864. XA_PRINT_WARNING(" %u charts with invalid parameterizations\n", invalidParamCount);
  8865. #if XA_PROFILE
  8866. XA_PRINT(" Chart groups\n");
  8867. uint32_t chartGroupCount = 0;
  8868. for (uint32_t i = 0; i < meshCount; i++) {
  8869. #if 0
  8870. XA_PRINT(" Mesh %u: %u chart groups\n", i, ctx->paramAtlas.chartGroupCount(i));
  8871. #endif
  8872. chartGroupCount += ctx->paramAtlas.chartGroupCount(i);
  8873. }
  8874. XA_PRINT(" %u total\n", chartGroupCount);
  8875. #endif
  8876. XA_PROFILE_PRINT_AND_RESET(" Compute charts total (real): ", computeChartsReal)
  8877. XA_PROFILE_PRINT_AND_RESET(" Compute charts total (thread): ", computeChartsThread)
  8878. XA_PROFILE_PRINT_AND_RESET(" Create face groups: ", createFaceGroups)
  8879. XA_PROFILE_PRINT_AND_RESET(" Extract invalid mesh geometry: ", extractInvalidMeshGeometry)
  8880. XA_PROFILE_PRINT_AND_RESET(" Chart group compute charts (real): ", chartGroupComputeChartsReal)
  8881. XA_PROFILE_PRINT_AND_RESET(" Chart group compute charts (thread): ", chartGroupComputeChartsThread)
  8882. XA_PROFILE_PRINT_AND_RESET(" Create chart group mesh: ", createChartGroupMesh)
  8883. XA_PROFILE_PRINT_AND_RESET(" Create colocals: ", createChartGroupMeshColocals)
  8884. XA_PROFILE_PRINT_AND_RESET(" Create boundaries: ", createChartGroupMeshBoundaries)
  8885. XA_PROFILE_PRINT_AND_RESET(" Build atlas: ", buildAtlas)
  8886. XA_PROFILE_PRINT_AND_RESET(" Init: ", buildAtlasInit)
  8887. XA_PROFILE_PRINT_AND_RESET(" Planar charts: ", planarCharts)
  8888. if (options.useInputMeshUvs) {
  8889. XA_PROFILE_PRINT_AND_RESET(" Original UV charts: ", originalUvCharts)
  8890. }
  8891. XA_PROFILE_PRINT_AND_RESET(" Clustered charts: ", clusteredCharts)
  8892. XA_PROFILE_PRINT_AND_RESET(" Place seeds: ", clusteredChartsPlaceSeeds)
  8893. XA_PROFILE_PRINT_AND_RESET(" Boundary intersection: ", clusteredChartsPlaceSeedsBoundaryIntersection)
  8894. XA_PROFILE_PRINT_AND_RESET(" Relocate seeds: ", clusteredChartsRelocateSeeds)
  8895. XA_PROFILE_PRINT_AND_RESET(" Reset: ", clusteredChartsReset)
  8896. XA_PROFILE_PRINT_AND_RESET(" Grow: ", clusteredChartsGrow)
  8897. XA_PROFILE_PRINT_AND_RESET(" Boundary intersection: ", clusteredChartsGrowBoundaryIntersection)
  8898. XA_PROFILE_PRINT_AND_RESET(" Merge: ", clusteredChartsMerge)
  8899. XA_PROFILE_PRINT_AND_RESET(" Fill holes: ", clusteredChartsFillHoles)
  8900. XA_PROFILE_PRINT_AND_RESET(" Copy chart faces: ", copyChartFaces)
  8901. XA_PROFILE_PRINT_AND_RESET(" Create chart mesh and parameterize (real): ", createChartMeshAndParameterizeReal)
  8902. XA_PROFILE_PRINT_AND_RESET(" Create chart mesh and parameterize (thread): ", createChartMeshAndParameterizeThread)
  8903. XA_PROFILE_PRINT_AND_RESET(" Create chart mesh: ", createChartMesh)
  8904. XA_PROFILE_PRINT_AND_RESET(" Parameterize charts: ", parameterizeCharts)
  8905. XA_PROFILE_PRINT_AND_RESET(" Orthogonal: ", parameterizeChartsOrthogonal)
  8906. XA_PROFILE_PRINT_AND_RESET(" LSCM: ", parameterizeChartsLSCM)
  8907. XA_PROFILE_PRINT_AND_RESET(" Recompute: ", parameterizeChartsRecompute)
  8908. XA_PROFILE_PRINT_AND_RESET(" Piecewise: ", parameterizeChartsPiecewise)
  8909. XA_PROFILE_PRINT_AND_RESET(" Boundary intersection: ", parameterizeChartsPiecewiseBoundaryIntersection)
  8910. XA_PROFILE_PRINT_AND_RESET(" Evaluate quality: ", parameterizeChartsEvaluateQuality)
  8911. #if XA_PROFILE_ALLOC
  8912. XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
  8913. #endif
  8914. XA_PRINT_MEM_USAGE
  8915. } else {
  8916. XA_PROFILE_START(computeChartsReal)
  8917. if (!internal::segment::computeUvMeshCharts(ctx->taskScheduler, ctx->uvMeshes, ctx->progressFunc, ctx->progressUserData)) {
  8918. XA_PRINT(" Cancelled by user\n");
  8919. return;
  8920. }
  8921. XA_PROFILE_END(computeChartsReal)
  8922. ctx->uvMeshChartsComputed = true;
  8923. // Count charts.
  8924. uint32_t chartCount = 0;
  8925. const uint32_t meshCount = ctx->uvMeshes.size();
  8926. for (uint32_t i = 0; i < meshCount; i++)
  8927. chartCount += ctx->uvMeshes[i]->charts.size();
  8928. XA_PRINT(" %u charts\n", chartCount);
  8929. XA_PROFILE_PRINT_AND_RESET(" Total (real): ", computeChartsReal)
  8930. XA_PROFILE_PRINT_AND_RESET(" Total (thread): ", computeChartsThread)
  8931. }
  8932. #if XA_PROFILE_ALLOC
  8933. XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
  8934. #endif
  8935. XA_PRINT_MEM_USAGE
  8936. }
  8937. void PackCharts(Atlas *atlas, PackOptions packOptions)
  8938. {
  8939. // Validate arguments and context state.
  8940. if (!atlas) {
  8941. XA_PRINT_WARNING("PackCharts: atlas is null.\n");
  8942. return;
  8943. }
  8944. Context *ctx = (Context *)atlas;
  8945. if (ctx->meshes.isEmpty() && ctx->uvMeshInstances.isEmpty()) {
  8946. XA_PRINT_WARNING("PackCharts: No meshes. Call AddMesh or AddUvMesh first.\n");
  8947. return;
  8948. }
  8949. if (ctx->uvMeshInstances.isEmpty()) {
  8950. if (!ctx->paramAtlas.chartsComputed()) {
  8951. XA_PRINT_WARNING("PackCharts: ComputeCharts must be called first.\n");
  8952. return;
  8953. }
  8954. } else if (!ctx->uvMeshChartsComputed) {
  8955. XA_PRINT_WARNING("PackCharts: ComputeCharts must be called first.\n");
  8956. return;
  8957. }
  8958. if (packOptions.texelsPerUnit < 0.0f) {
  8959. XA_PRINT_WARNING("PackCharts: PackOptions::texelsPerUnit is negative.\n");
  8960. packOptions.texelsPerUnit = 0.0f;
  8961. }
  8962. // Cleanup atlas.
  8963. DestroyOutputMeshes(ctx);
  8964. if (atlas->utilization) {
  8965. XA_FREE(atlas->utilization);
  8966. atlas->utilization = nullptr;
  8967. }
  8968. if (atlas->image) {
  8969. XA_FREE(atlas->image);
  8970. atlas->image = nullptr;
  8971. }
  8972. atlas->meshCount = 0;
  8973. // Pack charts.
  8974. XA_PROFILE_START(packChartsAddCharts)
  8975. internal::pack::Atlas packAtlas;
  8976. if (!ctx->uvMeshInstances.isEmpty()) {
  8977. for (uint32_t i = 0; i < ctx->uvMeshInstances.size(); i++)
  8978. packAtlas.addUvMeshCharts(ctx->uvMeshInstances[i]);
  8979. }
  8980. else
  8981. packAtlas.addCharts(ctx->taskScheduler, &ctx->paramAtlas);
  8982. XA_PROFILE_END(packChartsAddCharts)
  8983. XA_PROFILE_START(packCharts)
  8984. if (!packAtlas.packCharts(packOptions, ctx->progressFunc, ctx->progressUserData))
  8985. return;
  8986. XA_PROFILE_END(packCharts)
  8987. // Populate atlas object with pack results.
  8988. atlas->atlasCount = packAtlas.getNumAtlases();
  8989. atlas->chartCount = packAtlas.getChartCount();
  8990. atlas->width = packAtlas.getWidth();
  8991. atlas->height = packAtlas.getHeight();
  8992. atlas->texelsPerUnit = packAtlas.getTexelsPerUnit();
  8993. if (atlas->atlasCount > 0) {
  8994. atlas->utilization = XA_ALLOC_ARRAY(internal::MemTag::Default, float, atlas->atlasCount);
  8995. for (uint32_t i = 0; i < atlas->atlasCount; i++)
  8996. atlas->utilization[i] = packAtlas.getUtilization(i);
  8997. }
  8998. if (packOptions.createImage) {
  8999. atlas->image = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, atlas->atlasCount * atlas->width * atlas->height);
  9000. for (uint32_t i = 0; i < atlas->atlasCount; i++)
  9001. packAtlas.getImages()[i]->copyTo(&atlas->image[atlas->width * atlas->height * i], atlas->width, atlas->height, packOptions.padding);
  9002. }
  9003. XA_PROFILE_PRINT_AND_RESET(" Total: ", packCharts)
  9004. XA_PROFILE_PRINT_AND_RESET(" Add charts (real): ", packChartsAddCharts)
  9005. XA_PROFILE_PRINT_AND_RESET(" Add charts (thread): ", packChartsAddChartsThread)
  9006. XA_PROFILE_PRINT_AND_RESET(" Restore texcoords: ", packChartsAddChartsRestoreTexcoords)
  9007. XA_PROFILE_PRINT_AND_RESET(" Rasterize: ", packChartsRasterize)
  9008. XA_PROFILE_PRINT_AND_RESET(" Dilate (padding): ", packChartsDilate)
  9009. XA_PROFILE_PRINT_AND_RESET(" Find location: ", packChartsFindLocation)
  9010. XA_PROFILE_PRINT_AND_RESET(" Blit: ", packChartsBlit)
  9011. #if XA_PROFILE_ALLOC
  9012. XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
  9013. #endif
  9014. XA_PRINT_MEM_USAGE
  9015. XA_PRINT("Building output meshes\n");
  9016. XA_PROFILE_START(buildOutputMeshes)
  9017. int progress = 0;
  9018. if (ctx->progressFunc) {
  9019. if (!ctx->progressFunc(ProgressCategory::BuildOutputMeshes, 0, ctx->progressUserData))
  9020. return;
  9021. }
  9022. if (ctx->uvMeshInstances.isEmpty())
  9023. atlas->meshCount = ctx->meshes.size();
  9024. else
  9025. atlas->meshCount = ctx->uvMeshInstances.size();
  9026. atlas->meshes = XA_ALLOC_ARRAY(internal::MemTag::Default, Mesh, atlas->meshCount);
  9027. memset(atlas->meshes, 0, sizeof(Mesh) * atlas->meshCount);
  9028. if (ctx->uvMeshInstances.isEmpty()) {
  9029. uint32_t chartIndex = 0;
  9030. for (uint32_t i = 0; i < atlas->meshCount; i++) {
  9031. Mesh &outputMesh = atlas->meshes[i];
  9032. MeshPolygonMapping *meshPolygonMapping = ctx->meshPolygonMappings[i];
  9033. // One polygon can have many triangles. Don't want to process the same polygon more than once when counting indices, building chart faces etc.
  9034. internal::BitArray polygonTouched;
  9035. if (meshPolygonMapping) {
  9036. polygonTouched.resize(meshPolygonMapping->faceVertexCount.size());
  9037. polygonTouched.zeroOutMemory();
  9038. }
  9039. // Count and alloc arrays.
  9040. const internal::InvalidMeshGeometry &invalid = ctx->paramAtlas.invalidMeshGeometry(i);
  9041. outputMesh.vertexCount += invalid.vertices().length;
  9042. outputMesh.indexCount += invalid.faces().length * 3;
  9043. for (uint32_t cg = 0; cg < ctx->paramAtlas.chartGroupCount(i); cg++) {
  9044. const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, cg);
  9045. for (uint32_t c = 0; c < chartGroup->chartCount(); c++) {
  9046. const internal::param::Chart *chart = chartGroup->chartAt(c);
  9047. outputMesh.vertexCount += chart->originalVertexCount();
  9048. const uint32_t faceCount = chart->unifiedMesh()->faceCount();
  9049. if (meshPolygonMapping) {
  9050. // Map triangles back to polygons and count the polygon vertices.
  9051. for (uint32_t f = 0; f < faceCount; f++) {
  9052. const uint32_t polygon = meshPolygonMapping->triangleToPolygonMap[chart->mapFaceToSourceFace(f)];
  9053. if (!polygonTouched.get(polygon)) {
  9054. polygonTouched.set(polygon);
  9055. outputMesh.indexCount += meshPolygonMapping->faceVertexCount[polygon];
  9056. }
  9057. }
  9058. } else {
  9059. outputMesh.indexCount += faceCount * 3;
  9060. }
  9061. outputMesh.chartCount++;
  9062. }
  9063. }
  9064. outputMesh.vertexArray = XA_ALLOC_ARRAY(internal::MemTag::Default, Vertex, outputMesh.vertexCount);
  9065. outputMesh.indexArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputMesh.indexCount);
  9066. outputMesh.chartArray = XA_ALLOC_ARRAY(internal::MemTag::Default, Chart, outputMesh.chartCount);
  9067. XA_PRINT(" Mesh %u: %u vertices, %u triangles, %u charts\n", i, outputMesh.vertexCount, outputMesh.indexCount / 3, outputMesh.chartCount);
  9068. // Copy mesh data.
  9069. uint32_t firstVertex = 0;
  9070. {
  9071. const internal::InvalidMeshGeometry &mesh = ctx->paramAtlas.invalidMeshGeometry(i);
  9072. internal::ConstArrayView<uint32_t> faces = mesh.faces();
  9073. internal::ConstArrayView<uint32_t> indices = mesh.indices();
  9074. internal::ConstArrayView<uint32_t> vertices = mesh.vertices();
  9075. // Vertices.
  9076. for (uint32_t v = 0; v < vertices.length; v++) {
  9077. Vertex &vertex = outputMesh.vertexArray[v];
  9078. vertex.atlasIndex = -1;
  9079. vertex.chartIndex = -1;
  9080. vertex.uv[0] = vertex.uv[1] = 0.0f;
  9081. vertex.xref = vertices[v];
  9082. }
  9083. // Indices.
  9084. for (uint32_t f = 0; f < faces.length; f++) {
  9085. const uint32_t indexOffset = faces[f] * 3;
  9086. for (uint32_t j = 0; j < 3; j++)
  9087. outputMesh.indexArray[indexOffset + j] = indices[f * 3 + j];
  9088. }
  9089. firstVertex = vertices.length;
  9090. }
  9091. uint32_t meshChartIndex = 0;
  9092. for (uint32_t cg = 0; cg < ctx->paramAtlas.chartGroupCount(i); cg++) {
  9093. const internal::param::ChartGroup *chartGroup = ctx->paramAtlas.chartGroupAt(i, cg);
  9094. for (uint32_t c = 0; c < chartGroup->chartCount(); c++) {
  9095. const internal::param::Chart *chart = chartGroup->chartAt(c);
  9096. const internal::Mesh *unifiedMesh = chart->unifiedMesh();
  9097. const uint32_t faceCount = unifiedMesh->faceCount();
  9098. #if XA_CHECK_PARAM_WINDING
  9099. uint32_t flippedCount = 0;
  9100. for (uint32_t f = 0; f < faceCount; f++) {
  9101. const float area = mesh->computeFaceParametricArea(f);
  9102. if (area < 0.0f)
  9103. flippedCount++;
  9104. }
  9105. const char *type = "LSCM";
  9106. if (chart->type() == ChartType::Planar)
  9107. type = "planar";
  9108. else if (chart->type() == ChartType::Ortho)
  9109. type = "ortho";
  9110. else if (chart->type() == ChartType::Piecewise)
  9111. type = "piecewise";
  9112. if (flippedCount > 0) {
  9113. if (flippedCount == faceCount) {
  9114. XA_PRINT_WARNING("chart %u (%s): all face flipped\n", chartIndex, type);
  9115. } else {
  9116. XA_PRINT_WARNING("chart %u (%s): %u / %u faces flipped\n", chartIndex, type, flippedCount, faceCount);
  9117. }
  9118. }
  9119. #endif
  9120. // Vertices.
  9121. for (uint32_t v = 0; v < chart->originalVertexCount(); v++) {
  9122. Vertex &vertex = outputMesh.vertexArray[firstVertex + v];
  9123. vertex.atlasIndex = packAtlas.getChart(chartIndex)->atlasIndex;
  9124. XA_DEBUG_ASSERT(vertex.atlasIndex >= 0);
  9125. vertex.chartIndex = (int32_t)chartIndex;
  9126. const internal::Vector2 &uv = unifiedMesh->texcoord(chart->originalVertexToUnifiedVertex(v));
  9127. vertex.uv[0] = internal::max(0.0f, uv.x);
  9128. vertex.uv[1] = internal::max(0.0f, uv.y);
  9129. vertex.xref = chart->mapChartVertexToSourceVertex(v);
  9130. }
  9131. // Indices.
  9132. for (uint32_t f = 0; f < faceCount; f++) {
  9133. const uint32_t indexOffset = chart->mapFaceToSourceFace(f) * 3;
  9134. for (uint32_t j = 0; j < 3; j++) {
  9135. uint32_t outIndex = indexOffset + j;
  9136. if (meshPolygonMapping)
  9137. outIndex = meshPolygonMapping->triangleToPolygonIndicesMap[outIndex];
  9138. outputMesh.indexArray[outIndex] = firstVertex + chart->originalVertices()[f * 3 + j];
  9139. }
  9140. }
  9141. // Charts.
  9142. Chart *outputChart = &outputMesh.chartArray[meshChartIndex];
  9143. const int32_t atlasIndex = packAtlas.getChart(chartIndex)->atlasIndex;
  9144. XA_DEBUG_ASSERT(atlasIndex >= 0);
  9145. outputChart->atlasIndex = (uint32_t)atlasIndex;
  9146. outputChart->type = chart->isInvalid() ? ChartType::Invalid : chart->type();
  9147. if (meshPolygonMapping) {
  9148. // Count polygons.
  9149. polygonTouched.zeroOutMemory();
  9150. outputChart->faceCount = 0;
  9151. for (uint32_t f = 0; f < faceCount; f++) {
  9152. const uint32_t polygon = meshPolygonMapping->triangleToPolygonMap[chart->mapFaceToSourceFace(f)];
  9153. if (!polygonTouched.get(polygon)) {
  9154. polygonTouched.set(polygon);
  9155. outputChart->faceCount++;
  9156. }
  9157. }
  9158. // Write polygons.
  9159. outputChart->faceArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputChart->faceCount);
  9160. polygonTouched.zeroOutMemory();
  9161. uint32_t of = 0;
  9162. for (uint32_t f = 0; f < faceCount; f++) {
  9163. const uint32_t polygon = meshPolygonMapping->triangleToPolygonMap[chart->mapFaceToSourceFace(f)];
  9164. if (!polygonTouched.get(polygon)) {
  9165. polygonTouched.set(polygon);
  9166. outputChart->faceArray[of++] = polygon;
  9167. }
  9168. }
  9169. } else {
  9170. outputChart->faceCount = faceCount;
  9171. outputChart->faceArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputChart->faceCount);
  9172. for (uint32_t f = 0; f < outputChart->faceCount; f++)
  9173. outputChart->faceArray[f] = chart->mapFaceToSourceFace(f);
  9174. }
  9175. outputChart->material = 0;
  9176. meshChartIndex++;
  9177. chartIndex++;
  9178. firstVertex += chart->originalVertexCount();
  9179. }
  9180. }
  9181. XA_DEBUG_ASSERT(outputMesh.vertexCount == firstVertex);
  9182. XA_DEBUG_ASSERT(outputMesh.chartCount == meshChartIndex);
  9183. if (ctx->progressFunc) {
  9184. const int newProgress = int((i + 1) / (float)atlas->meshCount * 100.0f);
  9185. if (newProgress != progress) {
  9186. progress = newProgress;
  9187. if (!ctx->progressFunc(ProgressCategory::BuildOutputMeshes, progress, ctx->progressUserData))
  9188. return;
  9189. }
  9190. }
  9191. }
  9192. } else {
  9193. uint32_t chartIndex = 0;
  9194. for (uint32_t m = 0; m < ctx->uvMeshInstances.size(); m++) {
  9195. Mesh &outputMesh = atlas->meshes[m];
  9196. const internal::UvMeshInstance *mesh = ctx->uvMeshInstances[m];
  9197. // Alloc arrays.
  9198. outputMesh.vertexCount = mesh->texcoords.size();
  9199. outputMesh.indexCount = mesh->mesh->indices.size();
  9200. outputMesh.chartCount = mesh->mesh->charts.size();
  9201. outputMesh.vertexArray = XA_ALLOC_ARRAY(internal::MemTag::Default, Vertex, outputMesh.vertexCount);
  9202. outputMesh.indexArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputMesh.indexCount);
  9203. outputMesh.chartArray = XA_ALLOC_ARRAY(internal::MemTag::Default, Chart, outputMesh.chartCount);
  9204. XA_PRINT(" UV mesh %u: %u vertices, %u triangles, %u charts\n", m, outputMesh.vertexCount, outputMesh.indexCount / 3, outputMesh.chartCount);
  9205. // Copy mesh data.
  9206. // Vertices.
  9207. for (uint32_t v = 0; v < mesh->texcoords.size(); v++) {
  9208. Vertex &vertex = outputMesh.vertexArray[v];
  9209. vertex.uv[0] = mesh->texcoords[v].x;
  9210. vertex.uv[1] = mesh->texcoords[v].y;
  9211. vertex.xref = v;
  9212. const uint32_t meshChartIndex = mesh->mesh->vertexToChartMap[v];
  9213. if (meshChartIndex == UINT32_MAX) {
  9214. // Vertex doesn't exist in any chart.
  9215. vertex.atlasIndex = -1;
  9216. vertex.chartIndex = -1;
  9217. } else {
  9218. const internal::pack::Chart *chart = packAtlas.getChart(chartIndex + meshChartIndex);
  9219. vertex.atlasIndex = chart->atlasIndex;
  9220. vertex.chartIndex = (int32_t)chartIndex + meshChartIndex;
  9221. }
  9222. }
  9223. // Indices.
  9224. memcpy(outputMesh.indexArray, mesh->mesh->indices.data(), mesh->mesh->indices.size() * sizeof(uint32_t));
  9225. // Charts.
  9226. for (uint32_t c = 0; c < mesh->mesh->charts.size(); c++) {
  9227. Chart *outputChart = &outputMesh.chartArray[c];
  9228. const internal::pack::Chart *chart = packAtlas.getChart(chartIndex);
  9229. XA_DEBUG_ASSERT(chart->atlasIndex >= 0);
  9230. outputChart->atlasIndex = (uint32_t)chart->atlasIndex;
  9231. outputChart->faceCount = chart->faces.size();
  9232. outputChart->faceArray = XA_ALLOC_ARRAY(internal::MemTag::Default, uint32_t, outputChart->faceCount);
  9233. outputChart->material = chart->material;
  9234. for (uint32_t f = 0; f < outputChart->faceCount; f++)
  9235. outputChart->faceArray[f] = chart->faces[f];
  9236. chartIndex++;
  9237. }
  9238. if (ctx->progressFunc) {
  9239. const int newProgress = int((m + 1) / (float)atlas->meshCount * 100.0f);
  9240. if (newProgress != progress) {
  9241. progress = newProgress;
  9242. if (!ctx->progressFunc(ProgressCategory::BuildOutputMeshes, progress, ctx->progressUserData))
  9243. return;
  9244. }
  9245. }
  9246. }
  9247. }
  9248. if (ctx->progressFunc && progress != 100)
  9249. ctx->progressFunc(ProgressCategory::BuildOutputMeshes, 100, ctx->progressUserData);
  9250. XA_PROFILE_END(buildOutputMeshes)
  9251. XA_PROFILE_PRINT_AND_RESET(" Total: ", buildOutputMeshes)
  9252. #if XA_PROFILE_ALLOC
  9253. XA_PROFILE_PRINT_AND_RESET(" Alloc: ", alloc)
  9254. #endif
  9255. XA_PRINT_MEM_USAGE
  9256. }
  9257. void Generate(Atlas *atlas, ChartOptions chartOptions, PackOptions packOptions)
  9258. {
  9259. if (!atlas) {
  9260. XA_PRINT_WARNING("Generate: atlas is null.\n");
  9261. return;
  9262. }
  9263. Context *ctx = (Context *)atlas;
  9264. if (ctx->meshes.isEmpty() && ctx->uvMeshInstances.isEmpty()) {
  9265. XA_PRINT_WARNING("Generate: No meshes. Call AddMesh or AddUvMesh first.\n");
  9266. return;
  9267. }
  9268. ComputeCharts(atlas, chartOptions);
  9269. PackCharts(atlas, packOptions);
  9270. }
  9271. void SetProgressCallback(Atlas *atlas, ProgressFunc progressFunc, void *progressUserData)
  9272. {
  9273. if (!atlas) {
  9274. XA_PRINT_WARNING("SetProgressCallback: atlas is null.\n");
  9275. return;
  9276. }
  9277. Context *ctx = (Context *)atlas;
  9278. ctx->progressFunc = progressFunc;
  9279. ctx->progressUserData = progressUserData;
  9280. }
  9281. void SetAlloc(ReallocFunc reallocFunc, FreeFunc freeFunc)
  9282. {
  9283. internal::s_realloc = reallocFunc;
  9284. internal::s_free = freeFunc;
  9285. }
  9286. void SetPrint(PrintFunc print, bool verbose)
  9287. {
  9288. internal::s_print = print;
  9289. internal::s_printVerbose = verbose;
  9290. }
  9291. const char *StringForEnum(AddMeshError error)
  9292. {
  9293. if (error == AddMeshError::Error)
  9294. return "Unspecified error";
  9295. if (error == AddMeshError::IndexOutOfRange)
  9296. return "Index out of range";
  9297. if (error == AddMeshError::InvalidFaceVertexCount)
  9298. return "Invalid face vertex count";
  9299. if (error == AddMeshError::InvalidIndexCount)
  9300. return "Invalid index count";
  9301. return "Success";
  9302. }
  9303. const char *StringForEnum(ProgressCategory category)
  9304. {
  9305. if (category == ProgressCategory::AddMesh)
  9306. return "Adding mesh(es)";
  9307. if (category == ProgressCategory::ComputeCharts)
  9308. return "Computing charts";
  9309. if (category == ProgressCategory::PackCharts)
  9310. return "Packing charts";
  9311. if (category == ProgressCategory::BuildOutputMeshes)
  9312. return "Building output meshes";
  9313. return "";
  9314. }
  9315. } // namespace xatlas
  9316. #if XATLAS_C_API
  9317. static_assert(sizeof(xatlas::Chart) == sizeof(xatlasChart), "xatlasChart size mismatch");
  9318. static_assert(sizeof(xatlas::Vertex) == sizeof(xatlasVertex), "xatlasVertex size mismatch");
  9319. static_assert(sizeof(xatlas::Mesh) == sizeof(xatlasMesh), "xatlasMesh size mismatch");
  9320. static_assert(sizeof(xatlas::Atlas) == sizeof(xatlasAtlas), "xatlasAtlas size mismatch");
  9321. static_assert(sizeof(xatlas::MeshDecl) == sizeof(xatlasMeshDecl), "xatlasMeshDecl size mismatch");
  9322. static_assert(sizeof(xatlas::UvMeshDecl) == sizeof(xatlasUvMeshDecl), "xatlasUvMeshDecl size mismatch");
  9323. static_assert(sizeof(xatlas::ChartOptions) == sizeof(xatlasChartOptions), "xatlasChartOptions size mismatch");
  9324. static_assert(sizeof(xatlas::PackOptions) == sizeof(xatlasPackOptions), "xatlasPackOptions size mismatch");
  9325. #ifdef __cplusplus
  9326. extern "C" {
  9327. #endif
  9328. xatlasAtlas *xatlasCreate()
  9329. {
  9330. return (xatlasAtlas *)xatlas::Create();
  9331. }
  9332. void xatlasDestroy(xatlasAtlas *atlas)
  9333. {
  9334. xatlas::Destroy((xatlas::Atlas *)atlas);
  9335. }
  9336. xatlasAddMeshError xatlasAddMesh(xatlasAtlas *atlas, const xatlasMeshDecl *meshDecl, uint32_t meshCountHint)
  9337. {
  9338. return (xatlasAddMeshError)xatlas::AddMesh((xatlas::Atlas *)atlas, *(const xatlas::MeshDecl *)meshDecl, meshCountHint);
  9339. }
  9340. void xatlasAddMeshJoin(xatlasAtlas *atlas)
  9341. {
  9342. xatlas::AddMeshJoin((xatlas::Atlas *)atlas);
  9343. }
  9344. xatlasAddMeshError xatlasAddUvMesh(xatlasAtlas *atlas, const xatlasUvMeshDecl *decl)
  9345. {
  9346. return (xatlasAddMeshError)xatlas::AddUvMesh((xatlas::Atlas *)atlas, *(const xatlas::UvMeshDecl *)decl);
  9347. }
  9348. void xatlasComputeCharts(xatlasAtlas *atlas, const xatlasChartOptions *chartOptions)
  9349. {
  9350. xatlas::ComputeCharts((xatlas::Atlas *)atlas, chartOptions ? *(xatlas::ChartOptions *)chartOptions : xatlas::ChartOptions());
  9351. }
  9352. void xatlasPackCharts(xatlasAtlas *atlas, const xatlasPackOptions *packOptions)
  9353. {
  9354. xatlas::PackCharts((xatlas::Atlas *)atlas, packOptions ? *(xatlas::PackOptions *)packOptions : xatlas::PackOptions());
  9355. }
  9356. void xatlasGenerate(xatlasAtlas *atlas, const xatlasChartOptions *chartOptions, const xatlasPackOptions *packOptions)
  9357. {
  9358. xatlas::Generate((xatlas::Atlas *)atlas, chartOptions ? *(xatlas::ChartOptions *)chartOptions : xatlas::ChartOptions(), packOptions ? *(xatlas::PackOptions *)packOptions : xatlas::PackOptions());
  9359. }
  9360. void xatlasSetProgressCallback(xatlasAtlas *atlas, xatlasProgressFunc progressFunc, void *progressUserData)
  9361. {
  9362. xatlas::ProgressFunc pf;
  9363. *(void **)&pf = (void *)progressFunc;
  9364. xatlas::SetProgressCallback((xatlas::Atlas *)atlas, pf, progressUserData);
  9365. }
  9366. void xatlasSetAlloc(xatlasReallocFunc reallocFunc, xatlasFreeFunc freeFunc)
  9367. {
  9368. xatlas::SetAlloc((xatlas::ReallocFunc)reallocFunc, (xatlas::FreeFunc)freeFunc);
  9369. }
  9370. void xatlasSetPrint(xatlasPrintFunc print, bool verbose)
  9371. {
  9372. xatlas::SetPrint((xatlas::PrintFunc)print, verbose);
  9373. }
  9374. const char *xatlasAddMeshErrorString(xatlasAddMeshError error)
  9375. {
  9376. return xatlas::StringForEnum((xatlas::AddMeshError)error);
  9377. }
  9378. const char *xatlasProgressCategoryString(xatlasProgressCategory category)
  9379. {
  9380. return xatlas::StringForEnum((xatlas::ProgressCategory)category);
  9381. }
  9382. void xatlasMeshDeclInit(xatlasMeshDecl *meshDecl)
  9383. {
  9384. xatlas::MeshDecl init;
  9385. memcpy(meshDecl, &init, sizeof(init));
  9386. }
  9387. void xatlasUvMeshDeclInit(xatlasUvMeshDecl *uvMeshDecl)
  9388. {
  9389. xatlas::UvMeshDecl init;
  9390. memcpy(uvMeshDecl, &init, sizeof(init));
  9391. }
  9392. void xatlasChartOptionsInit(xatlasChartOptions *chartOptions)
  9393. {
  9394. xatlas::ChartOptions init;
  9395. memcpy(chartOptions, &init, sizeof(init));
  9396. }
  9397. void xatlasPackOptionsInit(xatlasPackOptions *packOptions)
  9398. {
  9399. xatlas::PackOptions init;
  9400. memcpy(packOptions, &init, sizeof(init));
  9401. }
  9402. #ifdef __cplusplus
  9403. } // extern "C"
  9404. #endif
  9405. #endif // XATLAS_C_API