*/}}

la_tns_kernel.c 184 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856
  1. /*
  2. * LaGUI: A graphical application framework.
  3. * Copyright (C) 2022-2023 Wu Yiming
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "la_5.h"
  19. #include <math.h>
  20. #include "freetype/ftadvanc.h"
  21. #include <png.h>
  22. #define HF 0.5
  23. // 1 2
  24. // 7 9 11 13 14
  25. // 3 4
  26. // 8 10 12 15 16
  27. // 5 6
  28. real TNS_LCD_SEG_16[16][4]={
  29. {0,0,HF,0},{HF,0,1,0},{0,0.5,HF,0.5},{HF,0.5,1,0.5},{0,1,HF,1},{HF,1,1,1},
  30. {0,0,0,HF},{0,HF,0,1},{0.5,0,0.5,HF},{0.5,HF,0.5,1},{1,0,1,HF},{1,HF,1,1},
  31. {0,0,HF,HF},{1,0,HF,HF},{0,1,HF,HF},{1,1,HF,HF},
  32. };
  33. char TNS_LCD_MAP_16[][16]={
  34. {1,1,0,0,1,1,1,1,0,0,1,1,0,1,1,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},//0-9
  35. {1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,0},{1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0},
  36. {0,0,1,1,0,0,1,0,1,1,0,0,0,0,0,0},{1,1,1,1,1,1,1,0,0,0,0,1,0,0,0,0},
  37. {1,1,1,1,1,1,1,1,0,0,0,1,0,0,0,0},{1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0},
  38. {1,1,1,1,1,1,1,1,0,0,1,1,0,0,0,0},{1,1,1,1,1,1,1,0,0,0,1,1,0,0,0,0},
  39. {1,1,1,1,0,0,1,1,0,0,1,1,0,0,0,0},{1,1,0,1,1,1,0,0,1,1,1,1,0,0,0,0},//A
  40. {1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,1,1,1,1,0,0,0,0},
  41. {1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0},{1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,0},
  42. {1,1,0,1,1,1,1,1,0,0,0,1,0,0,0,0},{0,0,1,1,0,0,1,1,0,0,1,1,0,0,0,0},
  43. {1,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0},{1,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0},
  44. {0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1},{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},
  45. {0,0,0,0,0,0,1,1,0,0,1,1,1,1,0,0},{0,0,0,0,0,0,1,1,0,0,1,1,1,0,0,1},
  46. {1,1,0,0,1,1,1,1,0,0,1,1,0,0,0,0},{1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0},
  47. {1,1,0,0,1,1,1,1,0,0,1,1,0,0,0,1},{1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1},
  48. {1,1,0,1,1,1,0,0,0,0,0,1,1,0,0,0},{1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0},
  49. {0,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,0},
  50. {0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
  51. {0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,1,1,0},
  52. {0,0,1,0,1,1,0,1,0,1,0,0,0,0,0,0},{0,0,0,1,1,1,0,0,1,1,0,1,0,0,0,0},//a
  53. {0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,0},{0,0,1,0,1,1,0,1,1,1,0,0,0,0,0,0},
  54. {0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0},{0,1,1,1,1,0,0,0,1,1,0,0,0,0,0,0},
  55. {0,1,0,1,1,1,0,1,1,0,1,1,0,0,0,0},{0,0,1,0,0,1,1,1,0,1,0,0,0,0,0,0},
  56. {1,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0},{0,1,0,1,1,1,0,0,0,0,0,1,0,0,0,0},
  57. {0,0,1,1,0,0,0,1,1,0,0,0,0,0,0,1},{1,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0},
  58. {0,0,1,1,0,0,0,1,0,1,0,1,0,0,0,0},{0,0,1,0,0,1,0,1,0,1,0,0,0,0,0,0},
  59. {0,0,1,1,1,1,0,1,0,0,0,1,0,0,0,0},{1,1,0,1,0,0,0,0,1,1,1,0,0,0,0,0},
  60. {1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0},{0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0},
  61. {0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1},{0,0,1,1,0,1,0,0,1,1,0,0,0,0,0,0},
  62. {0,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0},{0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0},
  63. {0,0,0,0,0,0,0,1,0,0,0,1,0,0,1,1},{0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1},
  64. {0,0,0,1,1,1,0,0,1,0,1,1,0,0,0,0},{0,0,1,0,1,1,0,0,0,0,0,0,0,0,1,0},
  65. };
  66. // 1
  67. // 4 6
  68. // 2
  69. // 5 7
  70. // 3
  71. real TNS_LCD_SEG_7[7][4]={ {0,0,1,0},{0,0.5,1,0.5},{0,1,1,1},
  72. {0,0,0,HF},{0,HF,0,1},{1,0,1,HF},{1,HF,1,1},
  73. };
  74. char TNS_LCD_MAP_7[][7]={
  75. {1,0,1,1,1,1,1},{0,0,0,0,0,1,1},{1,1,1,0,1,1,0},{1,1,1,0,0,1,1},{0,1,0,1,0,1,1},// 0-4
  76. {1,1,1,1,0,0,1},{1,1,1,1,1,0,1},{1,0,0,0,0,1,1},{1,1,1,1,1,1,1},{1,1,1,1,0,1,1},// 6-9
  77. };
  78. #undef HF
  79. int tKnlAttatchShader(tnsShader *tns);
  80. tnsShader *tKnlFindShader1i(int CustomIndex);
  81. void tKnlPushMatrix();
  82. void tKnlPopMatrix();
  83. laListHandle *tKnlGetTextureList();
  84. void tnsLoadIdentity44d(tnsMatrix44d m);
  85. void tnsMakeOrthoMatrix44d(tnsMatrix44d mProjection, real xMin, real xMax, real yMin, real yMax, real zMin, real zMax);
  86. void tnsMakePerspectiveMatrix44d(tnsMatrix44d mProjection, real fFov_rad, real fAspect, real zMin, real zMax);
  87. void tnsMakeTranslationMatrix44d(tnsMatrix44d mTrans, real x, real y, real z);
  88. void tnsMakeRotationMatrix44d(tnsMatrix44d m, real angle_rad, real x, real y, real z);
  89. void tnsMakeScaleMatrix44d(tnsMatrix44d m, real x, real y, real z);
  90. void tnsMultiply44d(tnsMatrix44d result, tnsMatrix44d l, tnsMatrix44d r);
  91. void tnsInitFirstLevel(tnsMatrixStack *tms);
  92. tnsMatrixStackItem *tKnlGetCurrentMatStackItem();
  93. void tnsAttach2DOffscreenBuffer(tnsOffscreen *target, GLuint attatchment, tnsTexture *use);
  94. void tnsDetach2DOffscreenBuffer(tnsOffscreen *target, GLuint which_attach_point);
  95. //=========================================================================================
  96. tnsMain *T;
  97. real DefaultZRange[2] = {0.1, 1000};
  98. //=======================================[SYS]
  99. extern LA MAIN;
  100. void InitGLRenderEnviornment(){
  101. glEnable(GL_SCISSOR_TEST);
  102. };
  103. #ifdef __linux__
  104. void tnsContextMakeCurrent(SYSGLCONTEXT context, SYSWINDOW win){
  105. glXMakeContextCurrent(MAIN.dpy, win, win, context); T->CurrentContext=context; T->CurrentWindow=win;
  106. tnsUnbindTexture(); tnsUseNoTexture();
  107. };
  108. #endif
  109. #ifdef _WIN32
  110. void tnsContextMakeCurrent(SYSGLCONTEXT context, SYSTEMDC hdc){
  111. wglMakeCurrent(hdc, context); T->CurrentContext=context; T->CurrentDC=hdc;
  112. tnsUnbindTexture(); tnsUseNoTexture();
  113. };
  114. #endif
  115. void tnsSwitchToCurrentWindowContext(laWindow* w){
  116. #ifdef __linux__
  117. tnsContextMakeCurrent(w->glc,w->win);
  118. #endif
  119. #ifdef _WIN32
  120. tnsContextMakeCurrent(w->glc,w->hdc);
  121. #endif
  122. };
  123. void tnsDeleteContext(SYSGLCONTEXT glc){
  124. #ifdef __linux__
  125. glXDestroyContext(MAIN.dpy,glc);
  126. #endif
  127. #ifdef _WIN32
  128. wglDeleteContext(glc);
  129. #endif
  130. for(tnsOffscreen* o=T->Offscreens.pFirst;o;o=o->Item.pNext){
  131. if(o->FboContext==glc){ o->FboContext=0; }
  132. }
  133. }
  134. void tnsBindVertexArray(GLuint vao){
  135. T->CurrentVAO=vao; glBindVertexArray(vao);
  136. }
  137. void tnsViewportWithScissor(int x, int y, int w, int h){
  138. tnsShader *current_shader = 0;
  139. glEnable(GL_SCISSOR_TEST);
  140. glViewport(x, y, w, h); glScissor(x, y, w, h);
  141. T->vsx=x;T->vsy=y;T->vsw=w;T->vsh=h;
  142. if ((current_shader = T->CurrentShader)){
  143. tnsResetViewMatrix();
  144. tnsShaderApplyView(current_shader, tnsGetViewMatrix());
  145. tnsResetModelMatrix();
  146. tnsShaderApplyModel(current_shader, tnsGetModelMatrix());
  147. }
  148. }
  149. void tnsViewport(int x, int y, int w, int h){
  150. glViewport(x, y, w, h);
  151. }
  152. //Must At Origion!
  153. //void UseWindowMatrix_WithScissor(laWndPlacement* wp){
  154. // tnsViewportWithScissor(0, 0, VAL2_CLIENT_W_H(*wp));
  155. // SetMatrix2Di(0, VAL2_CLIENT_W_H(*wp), 0);
  156. //};
  157. //void UseBlockMatrix_WithScissor(laBlockPlacement* bp){
  158. // tnsViewportWithScissor(bp->UpperLeftX,
  159. // bp->ClientHeight - bp->LowerRightY,
  160. // bp->LowerRightX - bp->UpperLeftX,
  161. // bp->LowerRightY - bp->UpperLeftY);
  162. // SetMatrix2Di(0, bp->LowerRightX - bp->UpperLeftX,
  163. // 0, bp->UpperLeftY - bp->LowerRightY);
  164. //};
  165. void DrawWireRect2dp(real x, real y, real x2, real y2){
  166. real Verts[8];
  167. tnsMakeQuad2d(Verts, x, y, x2, y, x2, y2, x, y2);
  168. tnsVertexArray2d(Verts, 4);
  169. tnsPackAs(GL_LINE_LOOP);
  170. };
  171. void DrawWireRect4ds(real x, real y, real w, real h){
  172. real Verts[8];
  173. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y + h, x, y + h);
  174. tnsVertexArray2d(Verts, 4);
  175. tnsPackAs(GL_LINE_LOOP);
  176. };
  177. void DrawWireRect4drs(real x, real y, real w, real h){
  178. real Verts[8];
  179. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y - h, x, y - h);
  180. tnsVertexArray2d(Verts, 4);
  181. tnsPackAs(GL_LINE_LOOP);
  182. };
  183. void DrawSoildRect4drs(real x, real y, real w, real h){
  184. real Verts[8];
  185. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y - h, x, y - h);
  186. tnsVertexArray2d(Verts, 4);
  187. tnsPackAs(GL_TRIANGLE_FAN);
  188. }
  189. void DrawWireCross4ds(real x, real y, real w, real h){
  190. real Verts[8];
  191. tnsMakeQuad2d(Verts, x, y, x + w, y + h, x + w, y, x, y + h);
  192. tnsVertexArray2d(Verts, 4);
  193. tnsPackAs(GL_LINES);
  194. };
  195. void DrawWireCross4drs(real x, real y, real w, real h){
  196. real Verts[8];
  197. tnsMakeQuad2d(Verts, x, y, x + w, y - h, x + w, y, x, y - h);
  198. tnsVertexArray2d(Verts, 4);
  199. tnsPackAs(GL_LINES);
  200. };
  201. void DrawGrid6f(real L, real R, real U, real B, real stepX, real stepY){
  202. //do nothing;
  203. }
  204. //=======================================[Shader]
  205. int tnsNextPowOf2(int i){
  206. int result = 2;
  207. while (result < i){
  208. result *= 2;
  209. }
  210. return result;
  211. }
  212. void tnsShaderMakeIndex(tnsShader *tns){
  213. int program;
  214. if (!tns) return;
  215. program = tns->glProgramID;
  216. tns->iModel = glGetUniformLocation(program, "mModel");
  217. tns->iProjection = glGetUniformLocation(program, "mProjection");
  218. tns->iProjectionInverse = glGetUniformLocation(program, "mProjectionInverse");
  219. tns->iView = glGetUniformLocation(program, "mView");
  220. //tns->iNormal = glGetUniformLocation(program, "mNormalScaler");
  221. tns->iShadow = glGetUniformLocation(program, "mShadow");
  222. tns->iVertex = glGetAttribLocation(program, "vVertex");
  223. tns->iNormal = glGetAttribLocation(program, "vNormal");
  224. tns->iColor = glGetAttribLocation(program, "vColor");
  225. tns->iUV = glGetAttribLocation(program, "vUV");
  226. tns->iTexColor = glGetUniformLocation(program, "TexColor");
  227. tns->iTexNormal = glGetUniformLocation(program, "TexNormal");
  228. tns->iTexGPos = glGetUniformLocation(program, "TexGPos");
  229. tns->iTexColorMS = glGetUniformLocation(program, "TexColorMS");
  230. tns->iMultiplyColor = glGetUniformLocation(program, "MultiplyColor");
  231. tns->iTextureMode = glGetUniformLocation(program, "TextureMode");
  232. tns->iColorMode = glGetUniformLocation(program, "ColorMode");
  233. tns->iHCYGamma = glGetUniformLocation(program, "HCYGamma");
  234. tns->iSampleAmount = glGetUniformLocation(program, "SampleAmount");
  235. tns->iUseNormal = glGetUniformLocation(program, "UseNormal");
  236. tns->iOutputColorSpace=glGetUniformLocation(program, "OutputColorSpace");
  237. tns->iInputColorSpace=glGetUniformLocation(program, "InputColorSpace");
  238. tns->iShowStripes=glGetUniformLocation(program, "ShowStripes");
  239. tns->iComposing=glGetUniformLocation(program, "Composing");
  240. tns->iComposingGamma=glGetUniformLocation(program, "ComposingGamma");
  241. tns->iComposingBlackpoint=glGetUniformLocation(program, "ComposingBlackpoint");
  242. if(tns->iTexColor>=0){glUniform1i(tns->iTexColor, 0);}
  243. if(tns->iTexColorMS>=0){glUniform1i(tns->iTexColorMS, 1);}
  244. tns->iDoOffset = glGetUniformLocation(program, "DoOffset");
  245. tns->iUseHalftone = glGetUniformLocation(program, "UseHalftone");
  246. tns->iHalftoneSize = glGetUniformLocation(program, "HalftoneSize");
  247. tns->uViewDir = glGetUniformLocation(program, "uViewDir");
  248. tns->uViewPos = glGetUniformLocation(program, "uViewPos");
  249. tns->uNear = glGetUniformLocation(program, "uNear");
  250. tns->uFar = glGetUniformLocation(program, "uFar");
  251. tns->uFOV = glGetUniformLocation(program, "uFOV");
  252. }
  253. void tnsShaderApplyProjection(tnsShader *tns, tnsMatrix44d m){
  254. tnsMatrix44f mf;
  255. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  256. tnsConvert44df(m, mf);
  257. glUniformMatrix4fv(tns->iProjection, 1, 0, mf);
  258. }
  259. void tnsShaderApplyProjectionInverse(tnsShader *tns, tnsMatrix44d m){
  260. tnsMatrix44f mf;
  261. tnsMatrix44d i;
  262. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  263. tnsInverse44d(i, m);
  264. tnsConvert44df(i, mf);
  265. glUniformMatrix4fv(tns->iProjectionInverse, 1, 0, mf);
  266. }
  267. void tnsShaderApplyModel(tnsShader *tns, tnsMatrix44d m){
  268. tnsMatrix44f mf;
  269. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  270. tnsConvert44df(m, mf);
  271. glUniformMatrix4fv(tns->iModel, 1, 0, mf);
  272. }
  273. void tnsShaderApplyView(tnsShader *tns, tnsMatrix44d m){
  274. tnsMatrix44f mf;
  275. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  276. tnsConvert44df(m, mf);
  277. glUniformMatrix4fv(tns->iView, 1, 0, mf);
  278. }
  279. void tnsShaderApplyNormalScaler(tnsShader *tns, tnsMatrix44d m){
  280. tnsMatrix44f mf;
  281. if (tns->iNormal == -1) return;
  282. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  283. tnsConvert44df(m, mf);
  284. glUniformMatrix4fv(tns->iNormal, 1, 0, mf);
  285. }
  286. void tnsShaderApplyShadowMatrix(tnsShader *tns, tnsMatrix44d m){
  287. tnsMatrix44f mf;
  288. if (tns->iShadow == -1) return;
  289. if (T->BindedShader != tns){ glUseProgram(tns->glProgramID); T->BindedShader = tns; }
  290. tnsConvert44df(m, mf);
  291. glUniformMatrix4fv(tns->iShadow, 1, 0, mf);
  292. }
  293. char* tnsEnsureShaderCommoms(char* Content, char* Library, char* Material){
  294. char* c=0,*c1=0;
  295. c1=strSub(Content,"#with TNS_SHADER_COLOR_COMMON",TNS_SHADER_COLOR_COMMON);
  296. c=strSub(c1,"#with LA_SHADER_LIB_FXAA",LA_SHADER_LIB_FXAA); free(c1);
  297. c1=strSub(c,"#with TNS_SHADER_MATERIAL",Material?Material:""); free(c);
  298. c=strSub(c1,"#with TNS_SHADER_LIBRARY",Library?Library:""); free(c1);
  299. return c;
  300. }
  301. int tnsNewVertexShader(char *Content){
  302. int status = 0;
  303. char error[1024];
  304. GLuint VertexShaderObject;
  305. tnsShader *s = 0;
  306. if (!Content) return -1;
  307. VertexShaderObject = glCreateShader(GL_VERTEX_SHADER);
  308. char* UseContent=tnsEnsureShaderCommoms(Content,0,0);
  309. glShaderSource(VertexShaderObject, 1, &UseContent, 0);
  310. glCompileShader(VertexShaderObject);
  311. glGetShaderiv(VertexShaderObject, GL_COMPILE_STATUS, &status);
  312. if (status == GL_FALSE){
  313. glGetShaderInfoLog(VertexShaderObject, sizeof(error), 0, error);
  314. printf("Vertex shader error:\n%s", error);
  315. glDeleteShader(VertexShaderObject); free(UseContent);
  316. return -1;
  317. }
  318. free(UseContent);
  319. return VertexShaderObject;
  320. }
  321. int tnsNewFragmentShaderMaterial(char *Content, char* Library, char* Material){
  322. int status = 0;
  323. char error[1024];
  324. GLuint FragmentShaderObject;
  325. tnsShader *s = 0;
  326. if (!Content) return -1;
  327. FragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER);
  328. char* UseContent=tnsEnsureShaderCommoms(Content,Library,Material);
  329. glShaderSource(FragmentShaderObject, 1, &UseContent, 0);
  330. glCompileShader(FragmentShaderObject);
  331. glGetShaderiv(FragmentShaderObject, GL_COMPILE_STATUS, &status);
  332. if (status == GL_FALSE){
  333. glGetShaderInfoLog(FragmentShaderObject, sizeof(error), 0, error);
  334. printf("Fragment shader error:\n%s", error);
  335. glDeleteShader(FragmentShaderObject); free(UseContent);
  336. return -1;
  337. }
  338. free(UseContent);
  339. return FragmentShaderObject;
  340. }
  341. int tnsNewFragmentShader(char *Content){
  342. return tnsNewFragmentShaderMaterial(Content,0,0);
  343. }
  344. int tnsNewGeometryShader(char *Content){
  345. int status = 0;
  346. char error[1024];
  347. GLuint GeometryShaderObject;
  348. tnsShader *s = 0;
  349. if (!Content) return -1;
  350. GeometryShaderObject = glCreateShader(GL_GEOMETRY_SHADER);
  351. char* UseContent=tnsEnsureShaderCommoms(Content,0,0);
  352. glShaderSource(GeometryShaderObject, 1, &UseContent, 0);
  353. glCompileShader(GeometryShaderObject);
  354. glGetShaderiv(GeometryShaderObject, GL_COMPILE_STATUS, &status);
  355. if (status == GL_FALSE){
  356. glGetShaderInfoLog(GeometryShaderObject, sizeof(error), 0, error);
  357. printf("Geometry shader error:\n%s", error);
  358. glDeleteShader(GeometryShaderObject); free(UseContent);
  359. return -1;
  360. }
  361. free(UseContent);
  362. return GeometryShaderObject;
  363. }
  364. tnsShader *tnsNewShaderProgram(int VertexShaderID, int FragmentShaderID, int GeometryShaderID){
  365. int vso = VertexShaderID;
  366. int fso = FragmentShaderID;
  367. int gso = GeometryShaderID;
  368. tnsShader *tns = 0;
  369. int status = 0;
  370. char error[1024];
  371. if (!vso || !fso) return 0;
  372. tns = CreateNew(tnsShader);
  373. tns->vtShaderID = vso;
  374. tns->fgShaderID = fso;
  375. tns->glProgramID = glCreateProgram();
  376. glAttachShader(tns->glProgramID, vso);
  377. glAttachShader(tns->glProgramID, fso);
  378. if (GeometryShaderID > -1){ glAttachShader(tns->glProgramID, gso); tns->gsShaderID=gso; }
  379. glLinkProgram(tns->glProgramID);
  380. glGetProgramiv(tns->glProgramID, GL_LINK_STATUS, &status);
  381. if (status == GL_FALSE){
  382. glGetProgramInfoLog(tns->glProgramID, sizeof(error), 0, error);
  383. printf("Shader Linking error:\n%s", error);
  384. glDetachShader(tns->glProgramID, vso);
  385. glDetachShader(tns->glProgramID, fso);
  386. glDeleteShader(vso);
  387. glDeleteShader(fso);
  388. glDeleteProgram(tns->glProgramID);
  389. FreeMem(tns);
  390. return 0;
  391. }
  392. glUseProgram(tns->glProgramID);
  393. tnsShaderMakeIndex(tns);
  394. return tns;
  395. }
  396. int tnsEnableShader(int index){
  397. tnsMatrixStackItem *tmsi;
  398. tnsShader *tns = tKnlFindShader1i(index);
  399. if (!tns){
  400. glUseProgram(0);
  401. T->CurrentShader = 0;
  402. T->BindedShader = 0;
  403. return 0;
  404. }
  405. glUseProgram(tns->glProgramID);
  406. T->CurrentShader = tns;
  407. T->BindedShader = tns;
  408. tmsi = tKnlGetCurrentMatStackItem();
  409. tnsShaderApplyProjection(tns, tmsi->projection);
  410. tnsShaderApplyView(tns, tmsi->view);
  411. tnsShaderApplyModel(tns, tmsi->model); tnsUseShader(tns);
  412. return 1;
  413. }
  414. int tnsEnableShaderv(tnsShader *shader){
  415. tnsMatrixStackItem *tmsi;
  416. tnsShader *s = shader;
  417. if (!s){ glUseProgram(0); T->CurrentShader = 0;T->BindedShader = 0; return 0; }
  418. glUseProgram(s->glProgramID);
  419. T->CurrentShader = s;
  420. T->BindedShader = s;
  421. tmsi = tKnlGetCurrentMatStackItem();
  422. tnsShaderApplyProjection(s, tmsi->projection);
  423. tnsShaderApplyProjectionInverse(s, tmsi->projection);
  424. tnsShaderApplyView(s, tmsi->view);
  425. tnsShaderApplyModel(s, tmsi->model); tnsUseShader(s);
  426. if(s->iUseNormal) glUniform1i(s->iUseNormal,T->SetUseNormal);
  427. if(s->uViewPos) glUniform3fv(s->uViewPos,1,T->SetViewPos);
  428. if(s->iUseHalftone) glUniform1f(s->iUseHalftone,T->SetUseHalftone);
  429. if(s->iHalftoneSize) glUniform1f(s->iHalftoneSize,T->SetHalftoneSize);
  430. //if(s->iTextureMode) glUniform1i(s->iTextureMode,T->StateTextureMode);
  431. //if(cs->iSampleAmount) glUniform1i(cs->iSampleAmount);
  432. return 1;
  433. }
  434. int tnsUseShader(tnsShader *shader){
  435. T->StateShader = shader;
  436. }
  437. void tnsDeleteShaderProgram(tnsShader* s){
  438. tnsUseShader(0); tnsEnableShaderv(0);
  439. if(s->vtShaderID>-1) glDeleteShader(s->vtShaderID);
  440. if(s->fgShaderID>-1) glDeleteShader(s->fgShaderID);
  441. if(s->gsShaderID>-1) glDeleteShader(s->gsShaderID);
  442. glDeleteProgram(s->glProgramID);
  443. free(s);
  444. }
  445. void tnsUseImmShader(){
  446. T->StateShader = T->immShader;
  447. }
  448. void tnsUseTransparentGridShader(){
  449. T->StateShader = T->TransparentGridShader;
  450. }
  451. void tnsUseExtraBufferShader(){
  452. T->StateShader = T->ExtraBuffersShader;
  453. }
  454. void tnsUseRayShader(){
  455. T->StateShader = T->RayShader;
  456. }
  457. void tnsUseShadowShader(){
  458. T->StateShader = T->ShadowShader;
  459. }
  460. void tnsUseSceneShader(){
  461. T->StateShader = T->SceneShader;
  462. }
  463. //=======================================[MAT]
  464. int tnsLineIntersectTest2d(tnsVector2d a1, tnsVector2d a2, tnsVector2d b1, tnsVector2d b2, double *aRatio){
  465. double k1, k2;
  466. double x;
  467. double y;
  468. double Ratio;
  469. double xDiff = (a2[0] - a1[0]); // +DBL_EPSILON;
  470. double xDiff2 = (b2[0] - b1[0]);
  471. if (xDiff == 0){
  472. if (xDiff2 == 0){
  473. *aRatio = 0;
  474. return 0;
  475. }
  476. double r2 = tnsGetRatiod(b1[0], b2[0], a1[0]);
  477. y = tnsLinearItp(b1[1], b2[1], r2);
  478. *aRatio = Ratio = tnsGetRatiod(a1[1], a2[1], y);
  479. }else{
  480. if (xDiff2 == 0){
  481. Ratio = tnsGetRatiod(a1[0], a2[0], b1[0]);
  482. //y = tnsLinearItp(a1[1], a2[1], r2);
  483. *aRatio = Ratio;
  484. }else{
  485. k1 = (a2[1] - a1[1]) / xDiff;
  486. k2 = (b2[1] - b1[1]) / xDiff2;
  487. if ((k1 == k2)) return 0;
  488. x = (a1[1] - b1[1] - k1 * a1[0] + k2 * b1[0]) / (k2 - k1);
  489. Ratio = (x - a1[0]) / xDiff;
  490. *aRatio = Ratio;
  491. }
  492. }
  493. if (b1[0] == b2[0]){
  494. y = tnsLinearItp(a1[1], a2[1], Ratio);
  495. if (y > TNS_MAX2(b1[1], b2[1]) || y < TNS_MIN2(b1[1], b2[1])) return 0;
  496. }else if (Ratio <= 0 || Ratio > 1 ||
  497. (b1[0] > b2[0] && x > b1[0]) ||
  498. (b1[0] < b2[0] && x < b1[0]) ||
  499. (b2[0] > b1[0] && x > b2[0]) ||
  500. (b2[0] < b1[0] && x < b2[0]))
  501. return 0;
  502. return 1;
  503. }
  504. double tnsGetLineZ(tnsVector3d L, tnsVector3d R, real Ratio){
  505. //double z = 1 / tnsLinearItp(1 / L[2], 1 / R[2], Ratio);
  506. double z = tnsLinearItp(L[2], R[2], Ratio);
  507. return z;
  508. }
  509. double tnsGetLineZPoint(tnsVector3d L, tnsVector3d R, tnsVector3d FromL){
  510. double r = (FromL[0] - L[0]) / (R[0] - L[0]);
  511. return tnsLinearItp(L[2], R[2], r);
  512. //return 1 / tnsLinearItp(1 / L[2], 1 / R[2], r);
  513. }
  514. double tnsGetRatio3d(tnsVector3d L, tnsVector3d R, tnsVector3d FromL){
  515. double r = (FromL[0] - L[0]) / (R[0] - L[0]);
  516. return r;
  517. }
  518. double tnsGetRatiod(real L, real R, real FromL){
  519. double r = (FromL - L) / (R - L);
  520. return r;
  521. }
  522. real tnsInterpolate(real L, real R, real T){
  523. return tnsLinearItp(L, R, T);
  524. }
  525. void tnsInterpolate2dv(real *L, real *R, real T, real *Result){
  526. Result[0] = tnsLinearItp(L[0], R[0], T);
  527. Result[1] = tnsLinearItp(L[1], R[1], T);
  528. }
  529. void tnsInterpolate3dv(real *L, real *R, real T, real *Result){
  530. Result[0] = tnsLinearItp(L[0], R[0], T);
  531. Result[1] = tnsLinearItp(L[1], R[1], T);
  532. Result[2] = tnsLinearItp(L[2], R[2], T);
  533. }
  534. void tnsInterpolateTripple2d(tnsVector2d v1, tnsVector2d v2, tnsVector2d v3, real ratio, tnsVector2d result){
  535. tnsVector2d i1,i2;
  536. tnsInterpolate2dv(v1,v2,ratio,i1);
  537. tnsInterpolate2dv(v2,v3,ratio,i2);
  538. tnsInterpolate2dv(i1,i2,ratio,result);
  539. }
  540. void tnsVectorMinus2d(tnsVector2d result, tnsVector2d l, tnsVector2d r){
  541. result[0] = l[0] - r[0];
  542. result[1] = l[1] - r[1];
  543. }
  544. void tnsVectorMinus3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  545. result[0] = l[0] - r[0];
  546. result[1] = l[1] - r[1];
  547. result[2] = l[2] - r[2];
  548. }
  549. void tnsVectorSubtract3d(tnsVector3d l, tnsVector3d r){
  550. l[0] = l[0] - r[0];
  551. l[1] = l[1] - r[1];
  552. l[2] = l[2] - r[2];
  553. }
  554. void tnsVectorPlus3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  555. result[0] = l[0] + r[0];
  556. result[1] = l[1] + r[1];
  557. result[2] = l[2] + r[2];
  558. }
  559. void tnsVectorAccum3d(tnsVector3d l, tnsVector3d r){
  560. l[0] = l[0] + r[0];
  561. l[1] = l[1] + r[1];
  562. l[2] = l[2] + r[2];
  563. }
  564. void tnsVectorAccum2d(tnsVector2d l, tnsVector2d r){
  565. l[0] = l[0] + r[0];
  566. l[1] = l[1] + r[1];
  567. }
  568. void tnsVectorNegate3d(tnsVector3d result, tnsVector3d l){
  569. result[0] = -l[0];
  570. result[1] = -l[1];
  571. result[2] = -l[2];
  572. }
  573. void tnsVectorNegateSelf3d(tnsVector3d l){
  574. l[0] = -l[0];
  575. l[1] = -l[1];
  576. l[2] = -l[2];
  577. }
  578. void tnsVectorCopy2d(tnsVector2d from, tnsVector2d to){
  579. to[0] = from[0];
  580. to[1] = from[1];
  581. }
  582. void tnsVectorCopy3d(tnsVector3d from, tnsVector3d to){
  583. to[0] = from[0];
  584. to[1] = from[1];
  585. to[2] = from[2];
  586. }
  587. void tnsVectorCopy4d(tnsVector4d from, tnsVector4d to){
  588. to[0] = from[0];
  589. to[1] = from[1];
  590. to[2] = from[2];
  591. to[3] = from[3];
  592. }
  593. void tnsVectorMultiSelf4d(tnsVector4d from, real num){
  594. from[0] *= num;
  595. from[1] *= num;
  596. from[2] *= num;
  597. from[3] *= num;
  598. }
  599. void tnsVectorMultiSelf3d(tnsVector3d from, real num){
  600. from[0] *= num;
  601. from[1] *= num;
  602. from[2] *= num;
  603. }
  604. void tnsVectorMultiSelf2d(tnsVector2d from, real num){
  605. from[0] *= num;
  606. from[1] *= num;
  607. }
  608. void tnsVectorMulti4d(tnsVector4d to, tnsVector4d from, real num){
  609. to[0]=from[0]*num;
  610. to[1]=from[1]*num;
  611. to[2]=from[2]*num;
  612. to[3]=from[3]*num;
  613. }
  614. void tnsVectorMulti3d(tnsVector3d to, tnsVector3d from, real num){
  615. to[0]=from[0]*num;
  616. to[1]=from[1]*num;
  617. to[2]=from[2]*num;
  618. }
  619. void tnsVectorMulti2d(tnsVector2d to, tnsVector2d from, real num){
  620. to[0]=from[0]*num;
  621. to[1]=from[1]*num;
  622. }
  623. real tnsDirectionToRad(tnsVector2d Dir){
  624. real arcc = acos(Dir[0]);
  625. real arcs = asin(Dir[1]);
  626. if (Dir[0] >= 0){
  627. if (Dir[1] >= 0) return arcc;
  628. else
  629. return TNS_PI * 2 - arcc;
  630. }else{
  631. if (Dir[1] >= 0) return arcs + TNS_PI / 2;
  632. else
  633. return TNS_PI + arcs;
  634. }
  635. }
  636. void tnsConvert44df(tnsMatrix44d from, tnsMatrix44f to){
  637. to[0] = from[0];
  638. to[1] = from[1];
  639. to[2] = from[2];
  640. to[3] = from[3];
  641. to[4] = from[4];
  642. to[5] = from[5];
  643. to[6] = from[6];
  644. to[7] = from[7];
  645. to[8] = from[8];
  646. to[9] = from[9];
  647. to[10] = from[10];
  648. to[11] = from[11];
  649. to[12] = from[12];
  650. to[13] = from[13];
  651. to[14] = from[14];
  652. to[15] = from[15];
  653. }
  654. void tnsLoadIdentity44d(tnsMatrix44d m){
  655. memset(m, 0, sizeof(tnsMatrix44d));
  656. m[0] = 1.0f;
  657. m[5] = 1.0f;
  658. m[10] = 1.0f;
  659. m[15] = 1.0f;
  660. };
  661. real tnsDistIdv2(real x1, real y1, real x2, real y2){
  662. real x = x2 - x1, y = y2 - y1;
  663. return sqrt((x * x + y * y));
  664. }
  665. real tnsDist3dv(tnsVector3d l, tnsVector3d r){
  666. real x = r[0] - l[0];
  667. real y = r[1] - l[1];
  668. real z = r[2] - l[2];
  669. return sqrt(x * x + y * y + z * z);
  670. }
  671. real tnsDist2dv(tnsVector2d l, tnsVector2d r){
  672. real x = r[0] - l[0];
  673. real y = r[1] - l[1];
  674. return sqrt(x * x + y * y);
  675. }
  676. real tnsLength3d(tnsVector3d l){
  677. return (sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]));
  678. }
  679. real tnsLength2d(tnsVector3d l){
  680. return (sqrt(l[0] * l[0] + l[1] * l[1]));
  681. }
  682. void tnsNormalize3d(tnsVector3d result, tnsVector3d l){
  683. real r = sqrt(l[0] * l[0] + l[1] * l[1] + l[2] * l[2]);
  684. result[0] = l[0] / r;
  685. result[1] = l[1] / r;
  686. result[2] = l[2] / r;
  687. }
  688. void tnsNormalize2d(tnsVector2d result, tnsVector2d l){
  689. real r = sqrt(l[0] * l[0] + l[1] * l[1]);
  690. result[0] = l[0] / r;
  691. result[1] = l[1] / r;
  692. }
  693. void tnsNormalizeSelf2d(tnsVector3d result){
  694. real r = sqrt(result[0] * result[0] + result[1] * result[1]);
  695. result[0] /= r;
  696. result[1] /= r;
  697. }
  698. void tnsNormalizeSelf3d(tnsVector3d result){
  699. real r = sqrt(result[0] * result[0] + result[1] * result[1] + result[2] * result[2]);
  700. result[0] /= r;
  701. result[1] /= r;
  702. result[2] /= r;
  703. }
  704. real tnsDot3d(tnsVector3d l, tnsVector3d r, int normalize){
  705. tnsVector3d ln, rn;
  706. if (normalize){
  707. tnsNormalize3d(ln, l);
  708. tnsNormalize3d(rn, r);
  709. return (ln[0] * rn[0] + ln[1] * rn[1] + ln[2] * rn[2]);
  710. }
  711. return (l[0] * r[0] + l[1] * r[1] + l[2] * r[2]);
  712. }
  713. real tnsDot2d(tnsVector2d l, tnsVector2d r, int normalize){
  714. tnsVector3d ln, rn;
  715. if (normalize){
  716. tnsNormalize2d(ln, l);
  717. tnsNormalize2d(rn, r);
  718. return (ln[0] * rn[0] + ln[1] * rn[1]);
  719. }
  720. return (l[0] * r[0] + l[1] * r[1]);
  721. }
  722. real tnsVectorCross3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  723. result[0] = l[1] * r[2] - l[2] * r[1];
  724. result[1] = l[2] * r[0] - l[0] * r[2];
  725. result[2] = l[0] * r[1] - l[1] * r[0];
  726. return tnsLength3d(result);
  727. }
  728. void tnsVectorCrossOnly3d(tnsVector3d result, tnsVector3d l, tnsVector3d r){
  729. result[0] = l[1] * r[2] - l[2] * r[1];
  730. result[1] = l[2] * r[0] - l[0] * r[2];
  731. result[2] = l[0] * r[1] - l[1] * r[0];
  732. }
  733. real tnsAngleRad3d(tnsVector3d from, tnsVector3d to, tnsVector3d PositiveReference){
  734. if (PositiveReference){
  735. tnsVector3d res;
  736. tnsVectorCross3d(res, from, to);
  737. if (tnsDot3d(res, PositiveReference, 1) > 0) return acosf(tnsDot3d(from, to, 1));
  738. else
  739. return -acosf(tnsDot3d(from, to, 1));
  740. }
  741. return acosf(tnsDot3d(from, to, 1));
  742. }
  743. void tnsApplyRotation33d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  744. result[0] = mat[0] * v[0] + mat[1] * v[1] + mat[2] * v[2];
  745. result[1] = mat[3] * v[0] + mat[4] * v[1] + mat[5] * v[2];
  746. result[2] = mat[6] * v[0] + mat[7] * v[1] + mat[8] * v[2];
  747. }
  748. void tnsApplyRotation43d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  749. result[0] = mat[0] * v[0] + mat[1] * v[1] + mat[2] * v[2];
  750. result[1] = mat[4] * v[0] + mat[5] * v[1] + mat[6] * v[2];
  751. result[2] = mat[8] * v[0] + mat[9] * v[1] + mat[10] * v[2];
  752. }
  753. void tnsApplyTransform43d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  754. real w;
  755. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * 1;
  756. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * 1;
  757. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * 1;
  758. w = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * 1;
  759. //result[0] /= w;
  760. //result[1] /= w;
  761. //result[2] /= w;
  762. }
  763. void tnsApplyNormalTransform43d(tnsVector3d result, tnsMatrix44d mat, tnsVector3d v){
  764. real w;
  765. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * 1;
  766. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * 1;
  767. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * 1;
  768. }
  769. void tnsApplyTransform44d(tnsVector4d result, tnsMatrix44d mat, tnsVector4d v){
  770. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * 1;
  771. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * 1;
  772. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * 1;
  773. result[3] = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * 1;
  774. }
  775. void tnsApplyTransform44dTrue(tnsVector4d result, tnsMatrix44d mat, tnsVector4d v){
  776. result[0] = mat[0] * v[0] + mat[4] * v[1] + mat[8] * v[2] + mat[12] * v[3];
  777. result[1] = mat[1] * v[0] + mat[5] * v[1] + mat[9] * v[2] + mat[13] * v[3];
  778. result[2] = mat[2] * v[0] + mat[6] * v[1] + mat[10] * v[2] + mat[14] * v[3];
  779. result[3] = mat[3] * v[0] + mat[7] * v[1] + mat[11] * v[2] + mat[15] * v[3];
  780. }
  781. void tnsRemoveTranslation44d(tnsMatrix44d result, tnsMatrix44d mat){
  782. tnsLoadIdentity44d(result);
  783. result[0] = mat[0];
  784. result[1] = mat[1];
  785. result[2] = mat[2];
  786. result[4] = mat[4];
  787. result[5] = mat[5];
  788. result[6] = mat[6];
  789. result[8] = mat[8];
  790. result[9] = mat[9];
  791. result[10] = mat[10];
  792. }
  793. void tnsClearTranslation44d(tnsMatrix44d mat){
  794. mat[3] = 0;
  795. mat[7] = 0;
  796. mat[11] = 0;
  797. }
  798. void tnsCopyMatrix44d(tnsMatrix44d from, tnsMatrix44d to);
  799. void tnsExtractXYZEuler44d(tnsMatrix44d _mat, real *xyz_result){
  800. real xRot, yRot, zRot;
  801. tnsMatrix44d mat; tnsCopyMatrix44d(_mat,mat);
  802. tnsNormalizeSelf3d(&mat[0]);
  803. tnsNormalizeSelf3d(&mat[4]);
  804. tnsNormalizeSelf3d(&mat[8]);
  805. if (mat[2] < 1){
  806. if (mat[2] > -1){
  807. yRot = asin(mat[2]);
  808. xRot = atan2(-mat[6], mat[10]);
  809. zRot = atan2(-mat[1], mat[0]);
  810. }else{
  811. yRot = -TNS_PI / 2;
  812. xRot = -atan2(-mat[4], mat[5]);
  813. zRot = 0;
  814. }
  815. }else{
  816. yRot = TNS_PI / 2;
  817. xRot = atan2(-mat[4], mat[5]);
  818. zRot = 0;
  819. }
  820. xyz_result[0] = -xRot;
  821. xyz_result[1] = -yRot;
  822. xyz_result[2] = -zRot;
  823. }
  824. void tnsExtractLocation44d(tnsMatrix44d mat, real *xyz_result){
  825. xyz_result[0] = mat[12];
  826. xyz_result[1] = mat[13];
  827. xyz_result[2] = mat[14];
  828. }
  829. void tnsExtractScale44d(tnsMatrix44d mat, real *xyz_result){
  830. xyz_result[0] = tnsLength3d(&mat[0]);
  831. xyz_result[1] = tnsLength3d(&mat[4]);
  832. xyz_result[2] = tnsLength3d(&mat[8]);
  833. }
  834. #define L(row, col) l[(col << 2) + row]
  835. #define R(row, col) r[(col << 2) + row]
  836. #define P(row, col) result[(col << 2) + row]
  837. void tnsPrintMatrix44d(tnsMatrix44d l){
  838. int i, j;
  839. for (i = 0; i < 4; i++){
  840. for (j = 0; j < 4; j++){
  841. printf("%.5f ", L(i, j));
  842. }
  843. printf("\n");
  844. }
  845. }
  846. void tnsCopyMatrix44d(tnsMatrix44d from, tnsMatrix44d to){
  847. memcpy(to, from, sizeof(tnsMatrix44d));
  848. }
  849. void tnsMultiply44d(tnsMatrix44d result, tnsMatrix44d l, tnsMatrix44d r){
  850. int i;
  851. for (i = 0; i < 4; i++){
  852. real ai0 = L(i, 0), ai1 = L(i, 1), ai2 = L(i, 2), ai3 = L(i, 3);
  853. P(i, 0) = ai0 * R(0, 0) + ai1 * R(1, 0) + ai2 * R(2, 0) + ai3 * R(3, 0);
  854. P(i, 1) = ai0 * R(0, 1) + ai1 * R(1, 1) + ai2 * R(2, 1) + ai3 * R(3, 1);
  855. P(i, 2) = ai0 * R(0, 2) + ai1 * R(1, 2) + ai2 * R(2, 2) + ai3 * R(3, 2);
  856. P(i, 3) = ai0 * R(0, 3) + ai1 * R(1, 3) + ai2 * R(2, 3) + ai3 * R(3, 3);
  857. }
  858. };
  859. void tnsInverse44d(tnsMatrix44d inverse, tnsMatrix44d mat){
  860. int i, j, k;
  861. double temp;
  862. tnsMatrix44d tempmat;
  863. real max;
  864. int maxj;
  865. tnsLoadIdentity44d(inverse);
  866. tnsCopyMatrix44d(mat, tempmat);
  867. for (i = 0; i < 4; i++){
  868. /* Look for row with max pivot */
  869. max = fabsf(tempmat[i * 5]);
  870. maxj = i;
  871. for (j = i + 1; j < 4; j++){
  872. if (fabsf(tempmat[j * 4 + i]) > max){
  873. max = fabsf(tempmat[j * 4 + i]);
  874. maxj = j;
  875. }
  876. }
  877. /* Swap rows if necessary */
  878. if (maxj != i){
  879. for (k = 0; k < 4; k++){
  880. real t;
  881. t = tempmat[i * 4 + k];
  882. tempmat[i * 4 + k] = tempmat[maxj * 4 + k];
  883. tempmat[maxj * 4 + k] = t;
  884. t = inverse[i * 4 + k];
  885. inverse[i * 4 + k] = inverse[maxj * 4 + k];
  886. inverse[maxj * 4 + k] = t;
  887. }
  888. }
  889. //if (UNLIKELY(tempmat[i][i] == 0.0f)) {
  890. // return false; /* No non-zero pivot */
  891. //}
  892. temp = (double)tempmat[i * 5];
  893. for (k = 0; k < 4; k++){
  894. tempmat[i * 4 + k] = (real)((double)tempmat[i * 4 + k] / temp);
  895. inverse[i * 4 + k] = (real)((double)inverse[i * 4 + k] / temp);
  896. }
  897. for (j = 0; j < 4; j++){
  898. if (j != i){
  899. temp = tempmat[j * 4 + i];
  900. for (k = 0; k < 4; k++){
  901. tempmat[j * 4 + k] -= (real)((double)tempmat[i * 4 + k] * temp);
  902. inverse[j * 4 + k] -= (real)((double)inverse[i * 4 + k] * temp);
  903. }
  904. }
  905. }
  906. }
  907. }
  908. void tnsMakeTranslationMatrix44d(tnsMatrix44d mTrans, real x, real y, real z){
  909. tnsLoadIdentity44d(mTrans);
  910. mTrans[12] = x;
  911. mTrans[13] = y;
  912. mTrans[14] = z;
  913. }
  914. void tnsMakePerspectiveMatrix44d(tnsMatrix44d mProjection, real fFov_rad, real fAspect, real zMin, real zMax){
  915. real yMax = zMin * tanf(fFov_rad * 0.5f);
  916. real yMin = -yMax;
  917. real xMin = yMin * fAspect;
  918. real xMax = -xMin;
  919. tnsLoadIdentity44d(mProjection);
  920. mProjection[0] = (2.0f * zMin) / (xMax - xMin);
  921. mProjection[5] = (2.0f * zMin) / (yMax - yMin);
  922. mProjection[8] = (xMax + xMin) / (xMax - xMin);
  923. mProjection[9] = (yMax + yMin) / (yMax - yMin);
  924. mProjection[10] = -((zMax + zMin) / (zMax - zMin));
  925. mProjection[11] = -1.0f;
  926. mProjection[14] = -((2.0f * (zMax * zMin)) / (zMax - zMin));
  927. mProjection[15] = 0.0f;
  928. }
  929. void tnsMakeZTrackingMatrix44d(tnsMatrix44d mat, tnsVector3d this, tnsVector3d that, tnsVector3d up){
  930. tnsVector4d fwd, l, t, rt;
  931. fwd[3] = l[3] = t[3] = rt[3] = 1;
  932. t[0] = up[0];
  933. t[1] = up[1];
  934. t[2] = up[2];
  935. fwd[0] = that[0] - this[0];
  936. fwd[1] = that[1] - this[1];
  937. fwd[2] = that[2] - this[2];
  938. tnsNormalizeSelf3d(fwd);
  939. tnsVectorCross3d(l, fwd, t);
  940. tnsNormalizeSelf3d(l);
  941. tnsVectorCross3d(rt, l, fwd);
  942. tnsNormalizeSelf3d(rt);
  943. tnsLoadIdentity44d(mat);
  944. mat[0] = l[0];
  945. mat[1] = l[1];
  946. mat[2] = l[2];
  947. mat[4] = rt[0];
  948. mat[5] = rt[1];
  949. mat[6] = rt[2];
  950. mat[8] = -fwd[0];
  951. mat[9] = -fwd[1];
  952. mat[10] = -fwd[2];
  953. }
  954. void tnsMakeZTrackingMatrixDelta44d(tnsMatrix44d mat, tnsVector3d delta, tnsVector3d up){
  955. tnsVector4d fwd, l, t, rt;
  956. fwd[3] = l[3] = t[3] = rt[3] = 1;
  957. t[0] = up[0];
  958. t[1] = up[1];
  959. t[2] = up[2];
  960. fwd[0] = delta[0];
  961. fwd[1] = delta[1];
  962. fwd[2] = delta[2];
  963. tnsLoadIdentity44d(mat);
  964. tnsVectorCross3d(l, t, fwd);
  965. tnsVectorCross3d(rt, fwd, l);
  966. tnsNormalizeSelf3d(l);
  967. tnsNormalizeSelf3d(rt);
  968. tnsNormalizeSelf3d(fwd);
  969. mat[0] = l[0];
  970. mat[1] = l[1];
  971. mat[2] = l[2];
  972. mat[4] = rt[0];
  973. mat[5] = rt[1];
  974. mat[6] = rt[2];
  975. mat[8] = fwd[0];
  976. mat[9] = fwd[1];
  977. mat[10] = fwd[2];
  978. }
  979. void tnsMakeOrthoMatrix44d(tnsMatrix44d mProjection, real xMin, real xMax, real yMin, real yMax, real zMin, real zMax){
  980. tnsLoadIdentity44d(mProjection);
  981. mProjection[0] = 2.0f / (xMax - xMin);
  982. mProjection[5] = 2.0f / (yMax - yMin);
  983. mProjection[10] = -2.0f / (zMax - zMin);
  984. mProjection[12] = -((xMax + xMin) / (xMax - xMin));
  985. mProjection[13] = -((yMax + yMin) / (yMax - yMin));
  986. mProjection[14] = -((zMax + zMin) / (zMax - zMin));
  987. mProjection[15] = 1.0f;
  988. }
  989. void tnsMakeRotationMatrix44d(tnsMatrix44d m, real angle_rad, real x_, real y_, real z_){
  990. float x = x_;
  991. float y = y_;
  992. float z = z_;
  993. float c = cos(angle_rad);
  994. float s = sin(angle_rad);
  995. tnsMatrix44d d={
  996. x*x*(1.0f-c)+c, x*y*(1.0f-c)-z*s, x*z*(1.0f-c)+y*s, 0.0f,
  997. y*x*(1.0f-c)+z*s, y*y*(1.0f-c)+c, y*z*(1.0f-c)-x*s, 0.0f,
  998. z*x*(1.0f-c)-y*s, z*y*(1.0f-c)+x*s, z*z*(1.0f-c)+c, 0.0f,
  999. 0.0f, 0.0f, 0.0f, 1.0f };
  1000. memcpy(m,d,sizeof(tnsMatrix44d));
  1001. }
  1002. void tnsMakeRotationXMatrix44d(tnsMatrix44d m, real angle_rad){
  1003. tnsLoadIdentity44d(m);
  1004. m[5] = cos(angle_rad);
  1005. m[6] = sin(angle_rad);
  1006. m[9] = -sin(angle_rad);
  1007. m[10] = cos(angle_rad);
  1008. }
  1009. void tnsMakeRotationYMatrix44d(tnsMatrix44d m, real angle_rad){
  1010. tnsLoadIdentity44d(m);
  1011. m[0] = cos(angle_rad);
  1012. m[2] = -sin(angle_rad);
  1013. m[8] = sin(angle_rad);
  1014. m[10] = cos(angle_rad);
  1015. }
  1016. void tnsMakeRotationZMatrix44d(tnsMatrix44d m, real angle_rad){
  1017. tnsLoadIdentity44d(m);
  1018. m[0] = cos(angle_rad);
  1019. m[1] = sin(angle_rad);
  1020. m[4] = -sin(angle_rad);
  1021. m[5] = cos(angle_rad);
  1022. }
  1023. void tnsMakeScaleMatrix44d(tnsMatrix44d m, real x, real y, real z){
  1024. tnsLoadIdentity44d(m);
  1025. m[0] = x; m[5] = y; m[10] = z;
  1026. }
  1027. void tnsMakeViewportMatrix44d(tnsMatrix44d m, real w, real h, real Far, real Near){
  1028. tnsLoadIdentity44d(m);
  1029. m[0] = w / 2;
  1030. m[5] = h / 2;
  1031. m[10] = (Far - Near) / 2;
  1032. m[12] = w / 2;
  1033. m[13] = h / 2;
  1034. m[14] = (Far + Near) / 2;
  1035. m[15] = 1;
  1036. //m[0] = 2/w;
  1037. //m[5] = 2/h;
  1038. //m[10] = 1;
  1039. //m[12] = 2/w;
  1040. //m[13] = 2/h;
  1041. //m[14] = 1;
  1042. //m[15] = 1;
  1043. }
  1044. int tnsIntersectPlaneRay(tnsVector3d n, tnsVector3d p0, tnsVector3d l0, tnsVector3d l, real* t){
  1045. float denom = tnsDot3d(n, l, 0);
  1046. if (denom > 1e-6){
  1047. tnsVector3d p0l0; tnsVectorMinus3d(p0l0,p0 ,l0);
  1048. (*t) = tnsDot3d(p0l0, n, 0) / denom;
  1049. return ((*t) >= 0);
  1050. }
  1051. return 0;
  1052. }
  1053. void tnsInitFirstLevel(tnsMatrixStack *tms){
  1054. tnsLoadIdentity44d(tms->level[0].model);
  1055. tnsLoadIdentity44d(tms->level[0].projection);
  1056. tnsLoadIdentity44d(tms->level[0].view);
  1057. }
  1058. //-------------------Export
  1059. void tnsOrtho(real xMin, real xMax, real yMin, real yMax, real zMin, real zMax){
  1060. tnsShader *current_shader = 0;
  1061. real *mat = tnsGetProjectionMatrix();
  1062. T->vol=xMin; T->vor=xMax; T->vou=yMax; T->vob=yMin;
  1063. tnsMakeOrthoMatrix44d(mat, xMin, xMax, yMin, yMax, zMin, zMax);
  1064. if (current_shader = T->CurrentShader){
  1065. tnsShaderApplyProjection(current_shader, mat);
  1066. }
  1067. }
  1068. void tnsPerspective(real fFov_rad, real fAspect, real zMin, real zMax){
  1069. tnsShader *current_shader = 0;
  1070. real *mat = tnsGetProjectionMatrix();
  1071. tnsMakePerspectiveMatrix44d(mat, fFov_rad, fAspect, zMin, zMax);
  1072. if (current_shader = T->CurrentShader){
  1073. tnsShaderApplyProjection(current_shader, mat);
  1074. }
  1075. }
  1076. void tnsTranslate3d(real x, real y, real z){
  1077. tnsShader *current_shader = 0;
  1078. real *mat = tnsGetModelMatrix();
  1079. tnsMatrix44d transmat, result;
  1080. tnsMakeTranslationMatrix44d(transmat, x, y, z);
  1081. tnsMultiply44d(result, mat, transmat);
  1082. memcpy(mat, result, sizeof(tnsMatrix44d));
  1083. if (current_shader = T->CurrentShader){
  1084. tnsShaderApplyModel(current_shader, result);
  1085. }
  1086. }
  1087. void tnsPreTranslate3d(real x, real y, real z){
  1088. tnsShader *current_shader = 0;
  1089. real *mat = tnsGetModelMatrix();
  1090. tnsMatrix44d transmat, result;
  1091. //glTranslatef(x, y, z);
  1092. tnsMakeTranslationMatrix44d(transmat, x, y, z);
  1093. tnsMultiply44d(result, mat, transmat);
  1094. memcpy(mat, result, sizeof(tnsMatrix44d));
  1095. }
  1096. void tnsRotate4d(real degrees, real x, real y, real z){
  1097. tnsShader *current_shader = 0;
  1098. real *mat = tnsGetModelMatrix();
  1099. tnsMatrix44d rotmat, result;
  1100. tnsMakeRotationMatrix44d(rotmat, rad(degrees), x, y, z);
  1101. tnsMultiply44d(result, mat, rotmat);
  1102. memcpy(mat, result, sizeof(tnsMatrix44d));
  1103. if (current_shader = T->CurrentShader){
  1104. tnsShaderApplyModel(current_shader, result);
  1105. }
  1106. }
  1107. void tnsPreRotate4d(real degrees, real x, real y, real z){
  1108. tnsShader *current_shader = 0;
  1109. real *mat = tnsGetModelMatrix();
  1110. tnsMatrix44d rotmat, result;
  1111. tnsMakeRotationMatrix44d(rotmat, rad(degrees), x, y, z);
  1112. tnsMultiply44d(result, mat, rotmat);
  1113. memcpy(mat, result, sizeof(tnsMatrix44d));
  1114. }
  1115. void tnsScale3d(real x, real y, real z){
  1116. tnsShader *current_shader = 0;
  1117. real *mat = tnsGetModelMatrix();
  1118. tnsMatrix44d scalemat, normal_scaler, result;
  1119. glScalef(x, y, z);
  1120. tnsMakeScaleMatrix44d(scalemat, x, y, z);
  1121. tnsMultiply44d(result, mat, scalemat);
  1122. memcpy(mat, result, sizeof(tnsMatrix44d));
  1123. if (current_shader = T->CurrentShader){
  1124. tnsShaderApplyModel(current_shader, result);
  1125. }
  1126. }
  1127. void tnsPreScale3d(real x, real y, real z){
  1128. tnsShader *current_shader = 0;
  1129. real *mat = tnsGetModelMatrix();
  1130. tnsMatrix44d scalemat, normal_scaler, result;
  1131. glScalef(x, y, z);
  1132. tnsMakeScaleMatrix44d(scalemat, x, y, z);
  1133. tnsMultiply44d(result, mat, scalemat);
  1134. memcpy(mat, result, sizeof(tnsMatrix44d));
  1135. }
  1136. void tKnlPopMatrix();
  1137. void tKnlPushMatrix();
  1138. void tnsPushMatrix(){
  1139. tKnlPushMatrix();
  1140. };
  1141. void tnsPopMatrix(){
  1142. tKnlPopMatrix();
  1143. }
  1144. //========================================[KNL]
  1145. void tnsSetRayShaderUniformTextures(tnsOffscreen* doff){
  1146. if(!doff)return;
  1147. tnsActiveTexture(GL_TEXTURE0); glBindTexture(doff->pColor[0]->GLTexType, doff->pColor[0]->GLTexHandle);
  1148. tnsActiveTexture(GL_TEXTURE1); glBindTexture(doff->pColor[1]->GLTexType, doff->pColor[1]->GLTexHandle);
  1149. tnsActiveTexture(GL_TEXTURE2); glBindTexture(doff->pColor[2]->GLTexType, doff->pColor[2]->GLTexHandle);
  1150. glUniform1i(T->RayShader->iTexColor, 0); glUniform1i(T->RayShader->iTexNormal, 1); glUniform1i(T->RayShader->iTexGPos, 2);
  1151. }
  1152. void tnsInit(){
  1153. T = memAcquire(sizeof(tnsMain));
  1154. T->World=memAcquire(sizeof(tnsWorld));
  1155. }
  1156. void tnsInitRenderKernel(int matrixStackLevel){
  1157. tnsCommand *c;
  1158. GLuint m_nQuadVAO;
  1159. T->GLVersionStr = glGetString(GL_VERSION);
  1160. T->GLVendorStr = glGetString(GL_VENDOR);
  1161. T->GLRendererStr = glGetString(GL_RENDERER);
  1162. T->GLSLVersionStr = glGetString(GL_SHADING_LANGUAGE_VERSION);
  1163. T->stack.max_level = matrixStackLevel;
  1164. T->stack.level = CreateNewBuffer(tnsMatrixStackItem, matrixStackLevel);
  1165. T->NextShaderIndex = 1;
  1166. T->BindedShader = -1;
  1167. tnsInitFirstLevel(&T->stack);
  1168. T->StateLineWidth=T->SetLineWidth=1; T->StatePointSize=T->SetPointSize=1;
  1169. arrEnsureLength(&T->Vert, T->NextVert, &T->MaxVert, sizeof(GLfloat));
  1170. glGenBuffers(1, &T->VertBufObject);
  1171. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1172. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1173. arrEnsureLength(&T->Color, T->NextColor, &T->MaxColor, sizeof(GLfloat));
  1174. glGenBuffers(1, &T->ColorBufObject);
  1175. glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  1176. glBufferData(GL_ARRAY_BUFFER, T->MaxColor * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1177. arrEnsureLength(&T->Normal, T->NextNormal, &T->MaxNormal, sizeof(GLfloat));
  1178. glGenBuffers(1, &T->NormalBufObject);
  1179. glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  1180. glBufferData(GL_ARRAY_BUFFER, T->MaxNormal * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1181. arrEnsureLength(&T->TexCoord, T->NextTexCoord, &T->MaxTexCoord, sizeof(GLfloat));
  1182. glGenBuffers(1, &T->TexCoordBufObject);
  1183. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  1184. glBufferData(GL_ARRAY_BUFFER, T->MaxTexCoord * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1185. arrEnsureLength(&T->Index, T->NextIndex, &T->MaxIndex, sizeof(GLuint));
  1186. glGenBuffers(1, &T->IndexBufObject);
  1187. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, T->IndexBufObject);
  1188. glBufferData(GL_ELEMENT_ARRAY_BUFFER, T->MaxIndex * sizeof(GLuint), 0, GL_DYNAMIC_DRAW);
  1189. arrEnsureLength(&T->DrawingCommand, T->NextCommand, &T->MaxCommand, sizeof(tnsCommand));
  1190. }
  1191. void tnsInitBuiltinShaders(){
  1192. T->immShader = tnsNewShaderProgram(
  1193. tnsNewVertexShader(LA_IMM_VERTEX_SHADER),tnsNewFragmentShader(LA_IMM_FRAGMENT_SHADER),-1);
  1194. T->TEST_MatcapShader = tnsNewShaderProgram(
  1195. tnsNewVertexShader(TNS_VERTEX_SIMPLE_MATCAP),
  1196. tnsNewFragmentShader(TNS_FRAGMENT_SIMPLE_MATCAP), -1);
  1197. T->TransparentGridShader = tnsNewShaderProgram(
  1198. tnsNewVertexShader(TNS_VERTEX_GRID),
  1199. tnsNewFragmentShader(TNS_FRAGMENT_TRANSPARNT_GRID), -1);
  1200. T->RayShader = tnsNewShaderProgram(
  1201. tnsNewVertexShader(LA_RAY_VERTEX_SHADER),
  1202. tnsNewFragmentShader(LA_RAY_FRAGMENT_SHADER), -1);
  1203. T->ShadowShader = tnsNewShaderProgram(
  1204. tnsNewVertexShader(LA_CASCADE_SHADOW_VERTEX_SHADER),
  1205. tnsNewFragmentShader(LA_CASCADE_SHADOW_FRAGMENT_SHADER), -1);
  1206. T->SceneShader = tnsNewShaderProgram(
  1207. tnsNewVertexShader(LA_SCENE_VERTEX_SHADER),
  1208. tnsNewFragmentShader(LA_SCENE_FRAGMENT_SHADER), -1);
  1209. T->SelectionShader = tnsNewShaderProgram(
  1210. tnsNewVertexShader(LA_SELECTION_VERTEX_SHADER),
  1211. tnsNewFragmentShader(LA_SELECTION_FRAGMENT_SHADER), -1);
  1212. T->FloorShader = tnsNewShaderProgram(
  1213. tnsNewVertexShader(LA_FLOOR_VERTEX_SHADER),
  1214. tnsNewFragmentShader(LA_FLOOR_FRAGMENT_SHADER), -1);
  1215. tnsUseShader(T->immShader);
  1216. tnsEnableShaderv(T->immShader);
  1217. }
  1218. void tnsInitWindowDefaultRenderConfig(){
  1219. tnsInitBuiltinShaders();
  1220. };
  1221. void tnsDeleteBuiltinShaders(){
  1222. tnsDeleteShaderProgram(T->immShader); T->immShader=0;
  1223. tnsDeleteShaderProgram(T->TEST_MatcapShader); T->TEST_MatcapShader=0;
  1224. tnsDeleteShaderProgram(T->TransparentGridShader); T->TransparentGridShader=0;
  1225. tnsDeleteShaderProgram(T->SelectionShader); T->SelectionShader=0;
  1226. tnsDeleteShaderProgram(T->FloorShader); T->FloorShader=0;
  1227. tnsDeleteShaderProgram(T->SceneShader); T->SceneShader=0;
  1228. tnsDeleteShaderProgram(T->ShadowShader); T->ShadowShader=0;
  1229. tnsDeleteShaderProgram(T->RayShader); T->RayShader=0;
  1230. }
  1231. void tnsQuitFontManager();
  1232. void tnsQuit(){
  1233. tnsQuitFontManager();
  1234. tnsObject*o;
  1235. while(o=lstPopItem(&T->World->AllObjects)){ tnsDestroyObject(o); }
  1236. while(o=lstPopItem(&T->World->RootObjects)){ tnsDestroyRootObject(o); }
  1237. //memFreeRemainingLeftNodes();
  1238. tnsDeleteBuiltinShaders();
  1239. tnsOffscreen* off; while(off=T->Offscreens.pFirst){ tnsDelete2DOffscreen(off); }
  1240. tnsTexture* t; while(t=T->Textures.pFirst){ tnsDeleteTexture(t); }
  1241. arrFree(&T->Vert, &T->MaxVert);
  1242. arrFree(&T->Color, &T->MaxColor);
  1243. arrFree(&T->Normal, &T->MaxNormal);
  1244. arrFree(&T->TexCoord, &T->MaxTexCoord);
  1245. arrFree(&T->Index, &T->MaxIndex);
  1246. arrFree(&T->DrawingCommand, &T->DrawingCommand);
  1247. glDeleteBuffers(1, &T->VertBufObject);
  1248. glDeleteBuffers(1, &T->ColorBufObject);
  1249. glDeleteBuffers(1, &T->NormalBufObject);
  1250. glDeleteBuffers(1, &T->TexCoordBufObject);
  1251. glDeleteBuffers(1, &T->IndexBufObject);
  1252. FreeMem(T->stack.level);
  1253. memFree(T->World);
  1254. memFree(T);
  1255. }
  1256. void tnsRestoreFromNanoVG(){
  1257. glBindVertexArray(T->CurrentVAO);
  1258. tnsUseImmShader(); tnsEnableShaderv(T->immShader);
  1259. glActiveTexture(GL_TEXTURE0);
  1260. glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,GL_ONE,GL_ONE_MINUS_SRC_ALPHA);
  1261. }
  1262. tnsMatrixStackItem *tKnlGetCurrentMatStackItem(){
  1263. return &T->stack.level[T->stack.current_level];
  1264. }
  1265. real *tnsGetModelMatrix(){
  1266. return tKnlGetCurrentMatStackItem()->model;
  1267. }
  1268. real *tnsGetViewMatrix(){
  1269. return tKnlGetCurrentMatStackItem()->view;
  1270. }
  1271. real *tnsGetProjectionMatrix(){
  1272. return tKnlGetCurrentMatStackItem()->projection;
  1273. }
  1274. void tnsGetMVMatrix(tnsMatrix44d r){
  1275. tnsMatrixStackItem *tmsi=tKnlGetCurrentMatStackItem();
  1276. tnsMatrix44d tmp;
  1277. tnsMultiply44d(r, tmsi->model, tmsi->view);
  1278. }
  1279. void tnsGetMVPMatrix(tnsMatrix44d r){
  1280. tnsMatrixStackItem *tmsi=tKnlGetCurrentMatStackItem();
  1281. tnsMatrix44d tmp;
  1282. tnsMultiply44d(tmp, tmsi->model, tmsi->view);
  1283. tnsMultiply44d(r, tmp, tmsi->projection);
  1284. }
  1285. void tnsResetModelMatrix(){
  1286. tnsLoadIdentity44d(tnsGetModelMatrix());
  1287. }
  1288. void tnsResetViewMatrix(){
  1289. tnsLoadIdentity44d(tnsGetViewMatrix());
  1290. }
  1291. void tnsResetProjectionMatrix(){
  1292. tnsLoadIdentity44d(tnsGetProjectionMatrix());
  1293. }
  1294. int tKnlAttatchShader(tnsShader *tns){
  1295. lstAppendItem(&T->Shaders, tns);
  1296. tns->CustomID = T->NextShaderIndex;
  1297. T->NextShaderIndex++;
  1298. return tns->CustomID;
  1299. };
  1300. int CMP_NUM_IsThisShader(tnsShader *tns, int *index){
  1301. return (tns->CustomID == *index);
  1302. }
  1303. tnsShader *tKnlFindShader1i(int CustomIndex){
  1304. return lstFindItem(&CustomIndex, CMP_NUM_IsThisShader, &T->Shaders);
  1305. }
  1306. void tKnlPushMatrix(){
  1307. tnsMatrixStack *tms = &T->stack;
  1308. tnsShader *current_shader = T->CurrentShader;
  1309. if (tms->current_level == tms->max_level || !current_shader) return;
  1310. memcpy(&tms->level[tms->current_level + 1], &tms->level[tms->current_level], sizeof(tnsMatrixStackItem));
  1311. tms->current_level++;
  1312. //tnsShaderApplyModel(current_shader,tms->level[tms->current_level].model);
  1313. //tnsShaderApplyView(current_shader,tms->level[tms->current_level].view);
  1314. //tnsShaderApplyProjection(current_shader,tms->level[tms->current_level].projection);
  1315. };
  1316. void tKnlPopMatrix(){
  1317. tnsMatrixStack *tms = &T->stack;
  1318. tnsShader *current_shader = T->CurrentShader;
  1319. if (tms->current_level == 0 || !current_shader) return;
  1320. tms->current_level--;
  1321. tnsShaderApplyModel(current_shader, tms->level[tms->current_level].model);
  1322. tnsShaderApplyView(current_shader, tms->level[tms->current_level].view);
  1323. tnsShaderApplyProjection(current_shader, tms->level[tms->current_level].projection);
  1324. }
  1325. laListHandle *tKnlGetTextureList(){
  1326. return &T->Textures;
  1327. }
  1328. tnsBatch *tnsCreateBatch(u32bit NumVert, int Dimension, float *Data, int NormalDimension, float *Normal, int ColorDimension, float *Colors){
  1329. tnsBatch *b = CreateNew(tnsBatch);
  1330. b->Dimension = Dimension;
  1331. b->NormalDimension=NormalDimension;
  1332. b->ColorDimension=ColorDimension;
  1333. b->NumVert = NumVert;
  1334. glGenBuffers(1, &b->VBO);
  1335. glBindBuffer(GL_ARRAY_BUFFER, b->VBO);
  1336. glBufferData(GL_ARRAY_BUFFER, NumVert * Dimension * sizeof(GLfloat), Data, GL_DYNAMIC_DRAW);
  1337. if (Normal){
  1338. glGenBuffers(1, &b->NBO); glBindBuffer(GL_ARRAY_BUFFER, b->NBO);
  1339. glBufferData(GL_ARRAY_BUFFER, NumVert * NormalDimension * sizeof(GLfloat), Normal, GL_DYNAMIC_DRAW);
  1340. b->HasNormal=1;
  1341. }
  1342. if (Colors){
  1343. glGenBuffers(1, &b->CBO); glBindBuffer(GL_ARRAY_BUFFER, b->CBO);
  1344. glBufferData(GL_ARRAY_BUFFER, NumVert * ColorDimension * sizeof(GLfloat), Colors, GL_DYNAMIC_DRAW);
  1345. b->HasColor=1;
  1346. }
  1347. return b;
  1348. }
  1349. tnsBatch *tnsCreateBatchi(u32bit NumVert, int Dimension, int *Data){
  1350. tnsBatch *b = CreateNew(tnsBatch);
  1351. b->Dimension = Dimension;
  1352. b->NumVert = NumVert;
  1353. glGenBuffers(1, &b->VBO);
  1354. glBindBuffer(GL_ARRAY_BUFFER, b->VBO);
  1355. glBufferData(GL_ARRAY_BUFFER, NumVert * Dimension * sizeof(GLuint), Data, GL_DYNAMIC_DRAW);
  1356. return b;
  1357. }
  1358. void tnsCommandUseUniformColor(tnsBatchCommand*c, real* color){
  1359. tnsVectorCopy4d(color, c->UniformColor);
  1360. c->UseUniformColor=1;
  1361. }
  1362. void tnsCommandUseMaterial(tnsBatchCommand*c, tnsMaterial* material){
  1363. c->Material=material;
  1364. }
  1365. void tnsCommandUseWidth(tnsBatchCommand*c, real width){
  1366. c->Width=width;
  1367. }
  1368. void tnsCommandOverrideColorArray(tnsBatchCommand*c, int VertCount, int ColorDimension, float* colors){
  1369. if(!colors) return;
  1370. c->OverrideColorArray=1;
  1371. glGenBuffers(1, &c->CBO); glBindBuffer(GL_ARRAY_BUFFER, c->CBO);
  1372. glBufferData(GL_ARRAY_BUFFER, VertCount* ColorDimension * sizeof(GLfloat), colors, GL_DYNAMIC_DRAW);
  1373. c->ColorDimension = ColorDimension;
  1374. }
  1375. tnsBatchCommand *tnsCreateCommand(tnsBatch *b, const char* name, u32bit ElementCount, int Dimension, GLenum DrawAs, u32bit *Elements, int HiddenByDefault){
  1376. tnsBatchCommand *bc = CreateNew(tnsBatchCommand);
  1377. bc->ElementCount = ElementCount;
  1378. bc->DrawAs = DrawAs;
  1379. bc->Dimension = Dimension;
  1380. bc->name=name;
  1381. bc->HiddenByDefault = HiddenByDefault;
  1382. if(Elements){
  1383. glGenBuffers(1, &bc->EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bc->EBO);
  1384. glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementCount * Dimension * sizeof(GLuint), Elements, GL_DYNAMIC_DRAW);
  1385. bc->DrawElements=1;
  1386. }else{ bc->EBO=-1; }
  1387. //int a = GetLastError();
  1388. lstAppendItem(&b->Branches, bc);
  1389. return bc;
  1390. }
  1391. void tnsDeleteBatch(tnsBatch *b){
  1392. tnsBatchCommand *bc, *NextBc;
  1393. glDeleteBuffers(1, &b->VBO);
  1394. if (b->NBO > -1) glDeleteBuffers(1, &b->NBO);
  1395. if (b->CBO > -1) glDeleteBuffers(1, &b->CBO);
  1396. for (bc = b->Branches.pFirst; bc; bc = NextBc){
  1397. NextBc = bc->Item.pNext;
  1398. lstRemoveItem(&b->Branches, bc);
  1399. if (bc->EBO > -1) glDeleteBuffers(1, &bc->EBO);
  1400. if (bc->CBO > -1) glDeleteBuffers(1, &bc->CBO);
  1401. FreeMem(bc);
  1402. }
  1403. FreeMem(b);
  1404. }
  1405. void tnsDrawBatchInitArrayStates(tnsBatch* batch){
  1406. tnsShader* cs=T->BindedShader;
  1407. glBindBuffer(GL_ARRAY_BUFFER, batch->VBO);
  1408. glEnableVertexAttribArray(cs->iVertex);
  1409. glVertexAttribPointer(cs->iVertex, batch->Dimension, GL_FLOAT, 0, 0, 0);
  1410. if(cs->iNormal>=0){
  1411. if(batch->HasNormal){
  1412. glBindBuffer(GL_ARRAY_BUFFER, batch->NBO); glEnableVertexAttribArray(cs->iNormal);
  1413. glVertexAttribPointer(cs->iNormal, batch->NormalDimension, GL_FLOAT, 0, 0, 0); tnsUniformUseNormal(cs,T->StateUseNormal);
  1414. }else{ glDisableVertexAttribArray(cs->iNormal); glVertexAttrib3f(cs->iNormal,0,0,1); tnsUniformUseNormal(cs,0); }
  1415. }
  1416. if(cs->iColor>=0){
  1417. if(batch->HasColor){
  1418. glBindBuffer(GL_ARRAY_BUFFER, batch->CBO); glEnableVertexAttribArray(cs->iColor);
  1419. glVertexAttribPointer(cs->iColor, batch->ColorDimension, GL_FLOAT, 0, 0, 0);
  1420. }
  1421. }
  1422. if(cs->iUV>=0){ glDisableVertexAttribArray(cs->iUV); }
  1423. tnsUniformUseTexture(cs, 0, 0);
  1424. }
  1425. int tnsDrawBatch(tnsBatch* batch, const char* OverrideCommand, real* OverrideUniformColor, int OverrideAsArray) {
  1426. if (!batch) return;
  1427. int Drawn=0; tnsShader *LastShader=T->BindedShader,*SaveShader=T->BindedShader; int NeedInit=1;
  1428. int IsOverrideColor=0; int PointSizeChanged=0,LineWidthChanged=0;
  1429. for (tnsBatchCommand* bc = batch->Branches.pFirst; bc; bc = bc->Item.pNext) {
  1430. if(OverrideCommand && !strSame(OverrideCommand, bc->name)){ continue; }
  1431. if(!OverrideCommand && bc->HiddenByDefault){ continue; }
  1432. if(NeedInit || (bc->Material && LastShader!=bc->Material->Shader) || ((!bc->Material)&&LastShader!=SaveShader)){
  1433. if(bc->Material && bc->Material->Shader){ LastShader=bc->Material->Shader;
  1434. tnsUseShader(LastShader); tnsEnableShaderv(LastShader);
  1435. }else{
  1436. tnsUseShader(SaveShader); tnsEnableShaderv(SaveShader);
  1437. }
  1438. tnsDrawBatchInitArrayStates(batch); NeedInit=0;
  1439. }
  1440. tnsShader* cs=T->BindedShader;
  1441. if(cs->iColor>-1){
  1442. if(bc->OverrideColorArray){
  1443. glBindBuffer(GL_ARRAY_BUFFER, bc->CBO); glEnableVertexAttribArray(cs->iColor);
  1444. glVertexAttribPointer(cs->iColor, bc->ColorDimension, GL_FLOAT, 0, 0, 0); IsOverrideColor=1;
  1445. }else{
  1446. if(batch->HasColor){ if(IsOverrideColor){ glBindBuffer(GL_ARRAY_BUFFER, batch->CBO); glEnableVertexAttribArray(cs->iColor);
  1447. glVertexAttribPointer(cs->iColor, batch->ColorDimension, GL_FLOAT, 0, 0, 0); }
  1448. }else{ glDisableVertexAttribArray(cs->iColor); glVertexAttrib4fv(cs->iColor,T->StateColor); }
  1449. }
  1450. if(bc->UseUniformColor || OverrideUniformColor){ glDisableVertexAttribArray(cs->iColor); IsOverrideColor=1;
  1451. if(OverrideUniformColor){ glVertexAttrib4f(cs->iColor,LA_COLOR4(OverrideUniformColor)); }
  1452. else glVertexAttrib4f(cs->iColor,LA_COLOR4(bc->UniformColor));
  1453. }
  1454. }
  1455. if(bc->DrawAs == GL_POINTS && bc->Width>1e-5){ glPointSize(bc->Width); PointSizeChanged=1; }
  1456. if((bc->DrawAs == GL_LINE_STRIP||bc->DrawAs == GL_LINES||bc->DrawAs == GL_LINE_LOOP) && bc->Width>1e-5){
  1457. glLineWidth(bc->Width); LineWidthChanged=1;
  1458. }
  1459. int DrawElements=OverrideAsArray?0:bc->DrawElements;
  1460. if(DrawElements){
  1461. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bc->EBO);
  1462. glDrawElements(bc->DrawAs, bc->ElementCount*bc->Dimension, GL_UNSIGNED_INT, 0);
  1463. }else{ glDrawArrays(bc->DrawAs,0,bc->ElementCount); }
  1464. Drawn++;
  1465. if(PointSizeChanged){ glPointSize(1); } if(LineWidthChanged){ glLineWidth(1); }
  1466. }
  1467. if(SaveShader!=LastShader){ tnsUseShader(SaveShader); tnsEnableShaderv(SaveShader); }
  1468. //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  1469. return Drawn;
  1470. }
  1471. //==========================*=======================[Texture]
  1472. int tnsGetTextureMemoryComponetCount(tnsTexture *t){
  1473. int Comp = 0;
  1474. int CompSize;
  1475. switch (t->GLTexBitsType){
  1476. case GL_RGB:
  1477. Comp = 3;
  1478. break;
  1479. case GL_RGBA:
  1480. Comp = 4;
  1481. break;
  1482. }
  1483. return t->Width * t->Height * Comp;
  1484. }
  1485. int tnsInit2DTexture(tnsTexture *t, GLint glInternalFormat, int w, int h, int Multisample){
  1486. if (!t) return 0;
  1487. if(0/*glInternalFormat==GL_DEPTH_COMPONENT32F*/){
  1488. t->Width = w;
  1489. t->Height = h;
  1490. t->GLTexBitsType = GL_DEPTH_COMPONENT32F;
  1491. t->GLTexType = GL_RENDERBUFFER;
  1492. t->Multisample = Multisample;
  1493. glGenRenderbuffers(1, &t->GLTexHandle);
  1494. tnsConfigure2DTexture(t);
  1495. }else{
  1496. t->Width = w;
  1497. t->Height = h;
  1498. t->GLTexBitsType = glInternalFormat;
  1499. t->GLTexType = Multisample?GL_TEXTURE_2D_MULTISAMPLE:GL_TEXTURE_2D;
  1500. t->Multisample = Multisample;
  1501. glGenTextures(1, &t->GLTexHandle);
  1502. tnsConfigure2DTexture(t);
  1503. }
  1504. return 1;
  1505. }
  1506. int tnsInit3DTexture(tnsTexture *t, GLint glInternalFormat, int w, int h, int slices){
  1507. if (!t) return 0;
  1508. t->Width = w;
  1509. t->Height = h;
  1510. t->GLTexBitsType = glInternalFormat;
  1511. t->GLTexType = GL_TEXTURE_3D;
  1512. glGenTextures(1, &t->GLTexHandle);
  1513. tnsConfigure3DTexture(t);
  1514. return 1;
  1515. }
  1516. void tnsConfigure2DTexture(tnsTexture *t){
  1517. tnsBindTexture(t);
  1518. if(t->GLTexType==GL_RENDERBUFFER){
  1519. if(t->Multisample){ glRenderbufferStorageMultisample(GL_RENDERBUFFER, t->Multisample, t->GLTexBitsType, t->Width, t->Height); }
  1520. else { glRenderbufferStorage(GL_RENDERBUFFER, t->GLTexBitsType, t->Width, t->Height); }
  1521. }else{
  1522. int isDepth=t->GLTexBitsType==GL_DEPTH_COMPONENT||t->GLTexBitsType==GL_DEPTH_COMPONENT16||
  1523. t->GLTexBitsType==GL_DEPTH_COMPONENT24||t->GLTexBitsType==GL_DEPTH_COMPONENT32F;
  1524. int format=isDepth?GL_DEPTH_COMPONENT:GL_RGBA; int type=GL_UNSIGNED_BYTE;
  1525. if(t->GLTexBitsType==GL_DEPTH_STENCIL){ format=GL_DEPTH_STENCIL; type=GL_UNSIGNED_INT_24_8_EXT; }
  1526. if(t->Multisample) glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, t->Multisample, t->GLTexBitsType, t->Width, t->Height, GL_TRUE);
  1527. else{ glTexImage2D(GL_TEXTURE_2D, 0, t->GLTexBitsType, t->Width, t->Height, 0, format, type, 0);
  1528. int a=glGetError();
  1529. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  1530. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  1531. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1532. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1533. //glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  1534. }
  1535. }
  1536. tnsUnbindTexture();
  1537. }
  1538. void tnsConfigure3DTexture(tnsTexture *t){
  1539. tnsBindTexture(t);
  1540. glTexImage3D(GL_TEXTURE_3D, 0, t->GLTexBitsType, t->Width, t->Height, t->Slices, 0, GL_RGBA, GL_FLOAT, 0);
  1541. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  1542. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  1543. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP);
  1544. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  1545. glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1546. //glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  1547. tnsUnbindTexture();
  1548. }
  1549. void tnsReconfigureTextureParameters(int Multisample){
  1550. laListHandle* l = tKnlGetTextureList();
  1551. for(tnsOffscreen* o=T->Offscreens.pFirst;o;o=o->Item.pNext){ tnsTexture* t;
  1552. for(int i=0;i<4;i++){
  1553. t=o->pColor[i];
  1554. if(t){
  1555. t->Multisample = Multisample;
  1556. int recreate=0;
  1557. if(t->Multisample){ if(t->GLTexType==GL_TEXTURE_2D){t->GLTexType=GL_TEXTURE_2D_MULTISAMPLE; recreate=1;}}
  1558. else { if(t->GLTexType==GL_TEXTURE_2D_MULTISAMPLE){t->GLTexType=GL_TEXTURE_2D; recreate=1;}}
  1559. if(recreate){
  1560. glDeleteTextures(1, &t->GLTexHandle);
  1561. glGenTextures(1, &t->GLTexHandle);
  1562. }
  1563. T->TexColor=0;
  1564. tnsConfigure2DTexture(t);
  1565. tnsAttach2DOffscreenBuffer(o, GL_COLOR_ATTACHMENT0+i, t);
  1566. }
  1567. }
  1568. t=o->pDepth;
  1569. if(t){ int recreate=0;
  1570. if((!t->Multisample && Multisample)||(t->Multisample && !Multisample)){ recreate=1; }
  1571. if(Multisample){ t->GLTexType=GL_TEXTURE_2D_MULTISAMPLE; }else{ t->GLTexType=GL_TEXTURE_2D; }
  1572. t->Multisample = Multisample;
  1573. if(recreate){
  1574. glDeleteTextures(1, &t->GLTexHandle);
  1575. glGenTextures(1, &t->GLTexHandle);
  1576. } T->TexColor=0;
  1577. tnsConfigure2DTexture(t);
  1578. tnsAttach2DOffscreenBuffer(o, GL_DEPTH_ATTACHMENT, t);
  1579. }
  1580. }
  1581. }
  1582. tnsTexture *tnsCreate2DTexture(GLint glInternalFormat, int w, int h, int Multisample){
  1583. tnsTexture *tex = memAcquire(sizeof(tnsTexture));
  1584. tnsInit2DTexture(tex, glInternalFormat, w, h, Multisample);
  1585. laNotifyUsers("tns.texture_list");
  1586. lstAppendItem(tKnlGetTextureList(), tex);
  1587. return tex;
  1588. };
  1589. tnsTexture *tnsCreate3DTexture(GLint glInternalFormat, int w, int h, int slices){
  1590. tnsTexture *tex = memAcquire(sizeof(tnsTexture));
  1591. tnsInit3DTexture(tex, glInternalFormat, w, h, slices);
  1592. laNotifyUsers("tns.texture_list");
  1593. lstAppendItem(tKnlGetTextureList(), tex);
  1594. return tex;
  1595. };
  1596. void tnsCopyScreenTo2DTexture(tnsTexture *target, int x_lower_left, int y_lower_left, int w, int h){
  1597. if(target->GLTexType!=GL_TEXTURE_2D) return;
  1598. tnsBindTexture(target);
  1599. glReadBuffer(GL_BACK);
  1600. glCopyTexSubImage2D(target->GLTexType, 0, 0, 0, x_lower_left, y_lower_left, w, h);
  1601. tnsUnbindTexture();
  1602. }
  1603. void tnsUniformUseOffset(tnsShader* s, int use){
  1604. glUniform1i(s->iDoOffset,use);
  1605. }
  1606. void tnsUseMaskTexture(tnsTexture *t){
  1607. if(!t){T->StateTextureMode=0; return;}
  1608. T->StateTexColor = t; T->StateTextureMode=1;
  1609. }
  1610. void tnsUseTexture(tnsTexture *t){
  1611. if(!t){T->StateTextureMode=0; return;}
  1612. if(t->GLTexType == GL_TEXTURE_2D){ T->StateTexColor = t; T->StateTextureMode=2; }
  1613. else if(t->GLTexType == GL_TEXTURE_2D_MULTISAMPLE){ T->StateTexColor = t; T->StateTextureMode=3; }
  1614. }
  1615. void tnsUseNoTexture(){
  1616. tnsUseTexture(0);
  1617. }
  1618. void tnsUseMultiplyColor(int enable){
  1619. T->StateMultiplyColor=enable?1:0;
  1620. }
  1621. void tnsUniformUseNormal(tnsShader* s, int Use){
  1622. if(T->SetUseNormal!=Use){ T->SetUseNormal=Use; glUniform1i(s->iUseNormal,Use); }
  1623. }
  1624. void tnsUseNormal(int Use){ T->StateUseNormal=Use; }
  1625. void tnsUniformUseHalftone(tnsShader* s, real Use){
  1626. if(T->SetUseHalftone!=Use){ T->SetUseHalftone=Use; glUniform1f(s->iUseHalftone,Use); }
  1627. }
  1628. void tnsUniformHalftoneSize(tnsShader* s, real Use){
  1629. if(T->SetHalftoneSize!=Use){ T->SetHalftoneSize=Use; glUniform1f(s->iHalftoneSize,Use); }
  1630. }
  1631. void tnsUseHalftone(real Factor){ T->StateUseHalftone=Factor; }
  1632. void tnsActiveTexture(GLenum tex){
  1633. if (T->GlTextureSets != tex) glActiveTexture(tex);
  1634. T->GlTextureSets = tex;
  1635. }
  1636. void tnsBindTexture(tnsTexture *t){
  1637. if ((!t) || T->TexColor==t) return;
  1638. if(t->GLTexType == GL_TEXTURE_2D){ tnsActiveTexture(GL_TEXTURE0); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t;}
  1639. elif(t->GLTexType == GL_TEXTURE_2D_MULTISAMPLE){ tnsActiveTexture(GL_TEXTURE1); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t;}
  1640. elif(t->GLTexType == GL_RENDERBUFFER){ glBindRenderbufferEXT(GL_RENDERBUFFER, t->GLTexHandle); T->TexRenderbuffer = t;}
  1641. elif(t->GLTexType == GL_TEXTURE_3D){ tnsActiveTexture(GL_TEXTURE0); glBindTexture(t->GLTexType, t->GLTexHandle); T->TexColor=t;}
  1642. }
  1643. void tnsUnbindTexture(){
  1644. if(T->TexRenderbuffer){ if(T->TexRenderbuffer->GLTexType == GL_RENDERBUFFER){ glBindRenderbufferEXT(GL_RENDERBUFFER, 0); T->TexRenderbuffer=0;}}
  1645. if(T->TexColor){
  1646. if(T->TexColor->GLTexType == GL_TEXTURE_2D){tnsActiveTexture(GL_TEXTURE0);}
  1647. else if(T->TexColor->GLTexType == GL_TEXTURE_2D_MULTISAMPLE){tnsActiveTexture(GL_TEXTURE1);}
  1648. else if(T->TexColor->GLTexType == GL_TEXTURE_3D){tnsActiveTexture(GL_TEXTURE0);}
  1649. glBindTexture(T->TexColor->GLTexType, 0); T->TexColor=0;
  1650. }
  1651. }
  1652. void tnsUniformUseTexture(tnsShader* s, int mode, int sample){
  1653. if(s->StateTextureMode != mode){ s->StateTextureMode=mode; glUniform1i(s->iTextureMode,mode); }
  1654. if(mode==3 && s->StateSampleAmount != sample){ s->StateSampleAmount=sample, glUniform1i(s->iSampleAmount,sample); }
  1655. }
  1656. void tnsUniformUseMultiplyColor(tnsShader* s, int enable){
  1657. int mode=enable?1:0;
  1658. if(s->StateMultiplyColor != mode){ s->StateMultiplyColor=mode; glUniform1i(s->iMultiplyColor,mode); }
  1659. }
  1660. void tnsUniformColorMode(tnsShader* s, int mode){
  1661. glUniform1i(s->iColorMode,mode);
  1662. }
  1663. void tnsUniformHCYGamma(tnsShader* s, float Gamma){
  1664. glUniform1f(s->iHCYGamma,Gamma);
  1665. }
  1666. void tnsUniformInputColorSpace(tnsShader* s, int ColorSpace){
  1667. glUniform1i(s->iInputColorSpace,ColorSpace);
  1668. }
  1669. void tnsUniformOutputColorSpace(tnsShader* s, int ColorSpace){
  1670. glUniform1i(s->iOutputColorSpace,ColorSpace);
  1671. }
  1672. void tnsUniformShowColorOverflowStripes(tnsShader* s, int Show){
  1673. glUniform1i(s->iShowStripes,Show);
  1674. }
  1675. void tnsUniformColorComposing(tnsShader* s, int Composing, real gamma, real blackpoint){
  1676. glUniform1i(s->iComposing,Composing); glUniform1f(s->iComposingGamma,gamma);
  1677. glUniform1f(s->iComposingBlackpoint,blackpoint);
  1678. }
  1679. void tnsDraw2DTextureDirectly(tnsTexture *t, real x, real y, real w, real h){
  1680. real Verts[8];
  1681. real UV[8] = {
  1682. 0.0f, 1.0f,
  1683. 1.0f, 1.0f,
  1684. 1.0f, 0.0f,
  1685. 0.0f, 0.0f};
  1686. tnsMakeQuad2d(Verts, x, y, x + w, y, x + w, y + h, x, y + h);
  1687. tnsUseTexture(t);
  1688. tnsVertexArray2d(Verts, 4);
  1689. tnsTexCoordArray2d(UV, 4);
  1690. tnsPackAs(GL_TRIANGLE_FAN);
  1691. }
  1692. void tnsDraw2DTextureArg(tnsTexture *t,
  1693. real x_upper_right, real y_upper_right, int w, int h,
  1694. real *MultiplyColor,
  1695. real LPadding, real RPadding, real TPadding, real BPadding){
  1696. real Verts[8];
  1697. real UV[8] = {
  1698. 0.0f + LPadding, 1.0f - TPadding,
  1699. 1.0f - RPadding, 1.0f - TPadding,
  1700. 1.0f - RPadding, 0.0f + BPadding,
  1701. 0.0f + LPadding, 0.0f + BPadding};
  1702. tnsMakeQuad2d(Verts,
  1703. x_upper_right, y_upper_right,
  1704. x_upper_right + w, y_upper_right,
  1705. x_upper_right + w, y_upper_right + h,
  1706. x_upper_right, y_upper_right + h);
  1707. if (MultiplyColor){ tnsColor4dv(MultiplyColor); tnsUseMultiplyColor(1); }
  1708. tnsUseTexture(t);
  1709. tnsVertexArray2d(Verts, 4);
  1710. tnsTexCoordArray2d(UV, 4);
  1711. tnsPackAs(GL_TRIANGLE_FAN);
  1712. tnsUseMultiplyColor(0);
  1713. }
  1714. void tnsDeleteTexture(tnsTexture *t){
  1715. laListHandle *lst = tKnlGetTextureList();
  1716. tnsUnbindTexture();
  1717. if (!t) return;
  1718. if (t->GLTexType == GL_RENDERBUFFER){
  1719. glBindRenderbufferEXT(GL_RENDERBUFFER, t->GLTexHandle);
  1720. glDeleteRenderbuffersEXT(1, &t->GLTexHandle);
  1721. }else{
  1722. //glBindTexture(t->GLTexType, 0);
  1723. glDeleteTextures(1, &t->GLTexHandle);
  1724. }
  1725. laNotifyUsers("tns.texture_list");
  1726. lstRemoveItem(lst, t);
  1727. if (t->DrawData) FreeMem(t->DrawData);
  1728. memFree(t);
  1729. }
  1730. int tnsTextureMemorySize(tnsTexture *t, int Mem){
  1731. int ElemSize;
  1732. if (Mem) return t->Width * t->Height * sizeof(void *);
  1733. switch (t->GLTexBitsType){
  1734. default:
  1735. case GL_RED:
  1736. ElemSize = sizeof(char) * 1;
  1737. break;
  1738. case GL_RG:
  1739. ElemSize = sizeof(char) * 2;
  1740. break;
  1741. case GL_RGB:
  1742. ElemSize = sizeof(char) * 3;
  1743. break;
  1744. case GL_RGBA:
  1745. ElemSize = sizeof(char) * 4;
  1746. break;
  1747. case GL_RGBA32F:
  1748. ElemSize = sizeof(float) * 4;
  1749. break;
  1750. case GL_DEPTH_COMPONENT32F:
  1751. ElemSize = sizeof(float);
  1752. break;
  1753. }
  1754. t->ElemSize = ElemSize;
  1755. return t->Width * t->Height * ElemSize;
  1756. }
  1757. tnsImage* tnsNewImage(void* MemPNG){
  1758. tnsImage* im=memAcquire(sizeof(tnsImage));
  1759. im->MemPNG=MemPNG; return im;
  1760. }
  1761. STRUCTURE(tnsPNGRead){
  1762. unsigned char* data;
  1763. size_t NextData;
  1764. };
  1765. static void _tns_png_read(png_struct *ps, png_byte *data, png_size_t length){
  1766. tnsPNGRead *PNGRead = (tnsPNGRead*)png_get_io_ptr(ps);
  1767. memcpy(data,&PNGRead->data[PNGRead->NextData],length);
  1768. PNGRead->NextData+=length;
  1769. }
  1770. void tnsUseImage(tnsImage* im){
  1771. png_structp png_ptr=0;
  1772. png_infop info_ptr=0;
  1773. if(im->UserCount==0){
  1774. tnsPNGRead PNGRead={0};
  1775. png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { goto cleanup_png_read; }
  1776. info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { goto cleanup_png_read; }
  1777. if (setjmp(png_jmpbuf(png_ptr))) { goto cleanup_png_read; }
  1778. PNGRead.data=im->MemPNG; png_set_read_fn(png_ptr, &PNGRead, _tns_png_read);
  1779. png_read_info(png_ptr, info_ptr);
  1780. png_set_swap(png_ptr);
  1781. if (png_get_interlace_type (png_ptr, info_ptr) != PNG_INTERLACE_NONE){ goto cleanup_png_read; }
  1782. png_byte ColorType = png_get_color_type(png_ptr, info_ptr);
  1783. png_byte BitDepth = png_get_bit_depth(png_ptr, info_ptr);
  1784. int HasAlpha = ColorType & PNG_COLOR_MASK_ALPHA;
  1785. if (ColorType == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); }
  1786. //if (ColorType == PNG_COLOR_TYPE_GRAY && BitDepth < 8) { png_set_expand_gray_1_2_4_to_8(png_ptr); }
  1787. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); HasAlpha = 1; }
  1788. if (BitDepth>8) {png_set_strip_16(png_ptr);} if (BitDepth<8) { png_set_expand(png_ptr); }
  1789. if (!HasAlpha) { png_set_add_alpha(png_ptr, 0xFFFF, PNG_FILLER_AFTER); }
  1790. if (ColorType == PNG_COLOR_TYPE_GRAY || ColorType == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); }
  1791. png_read_update_info(png_ptr, info_ptr);
  1792. if (png_get_bit_depth(png_ptr, info_ptr)!=8) { goto cleanup_png_read; }
  1793. if (png_get_color_type(png_ptr, info_ptr) != PNG_COLOR_TYPE_RGB_ALPHA){ goto cleanup_png_read; }
  1794. if (png_get_channels(png_ptr, info_ptr) != 4) { goto cleanup_png_read; }
  1795. int W = png_get_image_width(png_ptr, info_ptr);
  1796. int H = png_get_image_height(png_ptr, info_ptr);
  1797. unsigned char* buf=calloc(W*4,H*sizeof(unsigned char));
  1798. for(int i=0;i<H;i++){ png_read_row(png_ptr, &buf[((H-i-1)*W)*4], NULL); }
  1799. im->Texture=tnsCreate2DTexture(GL_RGBA8,W,H,0);
  1800. tnsBindTexture(im->Texture); glTexSubImage2D(GL_TEXTURE_2D,0,0,0,W,H,GL_RGBA,GL_UNSIGNED_BYTE,buf);
  1801. tnsUnbindTexture();
  1802. free(buf);
  1803. }
  1804. cleanup_png_read:
  1805. if(png_ptr && info_ptr) png_destroy_read_struct(&png_ptr,&info_ptr,0);
  1806. im->UserCount++;
  1807. }
  1808. void tnsStopUsingImage(tnsImage* im){
  1809. im->UserCount--;
  1810. if(im->UserCount<=0){ im->UserCount=0; tnsDeleteTexture(im->Texture); im->Texture=0; }
  1811. }
  1812. //====================================================[NEW RENDER KERNEL]
  1813. //=================[Immediate-style api]
  1814. void tnsColor4d(real r, real g, real b, real a){ tnsVectorSet4(T->StateColor,r,g,b,a); }
  1815. void tnsColor4dv(real *rgba){ tnsVectorSet4v(T->StateColor,rgba); }
  1816. void tnsLineWidth(real Width){ if(TNS_FLOAT_CLOSE_ENOUGH_WIDER(Width,T->StateLineWidth)) return;
  1817. T->StateLineWidth=Width;
  1818. }
  1819. void tnsPointSize(real PointSize){ if(TNS_FLOAT_CLOSE_ENOUGH_WIDER(PointSize,T->StatePointSize)) return;
  1820. T->StatePointSize=PointSize;
  1821. }
  1822. void tnsVertex3d(real x, real y, real z){
  1823. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1824. int vend = c->VertEnd;
  1825. c->UseVert = 1;
  1826. if (!c->Dimensions) c->Dimensions = 3;
  1827. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions, &T->MaxVert, sizeof(GLfloat))){
  1828. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1829. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1830. }
  1831. GLfloat *varr = T->Vert;
  1832. if (c->Dimensions == 3){
  1833. varr[vend] = x;
  1834. varr[vend + 1] = y;
  1835. varr[vend + 2] = z;
  1836. c->NumVert++;
  1837. T->NextVert += 3;
  1838. c->VertEnd += 3;
  1839. }else{
  1840. varr[vend] = x;
  1841. varr[vend + 1] = y;
  1842. c->NumVert++;
  1843. T->NextVert += 2;
  1844. c->VertEnd += 2;
  1845. }
  1846. }
  1847. void tnsVertex2d(real x, real y){
  1848. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1849. int vend = c->VertEnd;
  1850. c->UseVert = 1;
  1851. if (!c->Dimensions) c->Dimensions = 2;
  1852. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions, &T->MaxVert, sizeof(GLfloat))){
  1853. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1854. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1855. }
  1856. GLfloat *varr = T->Vert;
  1857. if (c->Dimensions == 2){
  1858. varr[vend] = x;
  1859. varr[vend + 1] = y;
  1860. c->NumVert++;
  1861. T->NextVert += 2;
  1862. c->VertEnd += 2;
  1863. }else{
  1864. tnsVertex3d(x, y, 0.0f);
  1865. }
  1866. }
  1867. void tnsVertexArray2d(real *verts, int amount){
  1868. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1869. int trans = 2 * amount;
  1870. int vend = c->VertEnd;
  1871. c->UseVert = 1;
  1872. if (!c->Dimensions) c->Dimensions = 2;
  1873. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions*amount, &T->MaxVert, sizeof(GLfloat))){
  1874. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1875. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1876. }
  1877. GLfloat *varr = T->Vert;
  1878. if (c->Dimensions == 2){
  1879. int i;
  1880. for (i = 0; i < trans; i++){
  1881. varr[vend] = verts[i];
  1882. vend++;
  1883. }
  1884. //memcpy(&varr[vend], verts, trans*sizeof(real));
  1885. c->VertEnd += trans;
  1886. c->NumVert += amount;
  1887. T->NextVert += trans;
  1888. }
  1889. }
  1890. void tnsVertexArray3d(real *verts, int amount){
  1891. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1892. int trans = 3 * amount;
  1893. int vend = c->VertEnd;
  1894. c->UseVert = 1;
  1895. if (!c->Dimensions) c->Dimensions = 3;
  1896. if(arrEnsureLength(&T->Vert, T->NextVert+c->Dimensions*amount, &T->MaxVert, sizeof(GLfloat))){
  1897. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  1898. glBufferData(GL_ARRAY_BUFFER, T->MaxVert * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1899. }
  1900. GLfloat *varr = T->Vert;
  1901. if (c->Dimensions == 3){
  1902. int i;
  1903. for (i = 0; i < trans; i++){
  1904. varr[vend] = verts[i];
  1905. vend++;
  1906. }
  1907. //memcpy(&varr[vend], verts, trans*sizeof(real));
  1908. c->VertEnd += trans;
  1909. c->NumVert += amount;
  1910. T->NextVert += trans;
  1911. }
  1912. }
  1913. void tnsColorArray4d(real *colors, int amount){
  1914. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1915. int trans = 4 * amount;
  1916. int ofst = c->ColorEnd;
  1917. c->UseColor = 1;
  1918. if(arrEnsureLength(&T->Color, T->NextColor+4*amount, &T->MaxColor, sizeof(GLfloat))){
  1919. glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  1920. glBufferData(GL_ARRAY_BUFFER, T->MaxColor * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1921. }
  1922. GLfloat *carr = T->Color;
  1923. int i;
  1924. for (i = 0; i < trans; i++){
  1925. carr[ofst] = colors[i];
  1926. ofst++;
  1927. }
  1928. //memcpy(&T->Color[c->ColorEnd], colors, trans*sizeof(real));
  1929. c->ColorEnd += trans;
  1930. T->NextColor += trans;
  1931. }
  1932. void tnsNormalArray3d(real *normals, int amount){
  1933. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1934. int trans = 3 * amount;
  1935. int ofst = c->NormalEnd;
  1936. c->UseNormal = 1;
  1937. if(arrEnsureLength(&T->Normal, T->NextNormal+3*amount, &T->MaxNormal, sizeof(GLfloat))){
  1938. glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  1939. glBufferData(GL_ARRAY_BUFFER, T->MaxNormal * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1940. }
  1941. GLfloat *narr = T->Normal;
  1942. int i;
  1943. for (i = 0; i < trans; i++){
  1944. narr[ofst] = normals[i];
  1945. ofst++;
  1946. }
  1947. //memcpy(&T->Normal[c->NormalEnd], normals, trans*sizeof(real));
  1948. c->NormalEnd += trans;
  1949. T->NextNormal += trans;
  1950. }
  1951. void tnsTexCoordArray2d(real *coords, int amount){
  1952. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1953. int trans = 2 * amount;
  1954. int ofst = c->TexCoordEnd;
  1955. c->UseTexCoord = 1;
  1956. c->UVDimensions = 2;
  1957. if(arrEnsureLength(&T->TexCoord, T->NextTexCoord+2*amount, &T->MaxTexCoord, sizeof(GLfloat))){
  1958. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  1959. glBufferData(GL_ARRAY_BUFFER, T->MaxTexCoord * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1960. }
  1961. GLfloat *carr = T->TexCoord;
  1962. int i;
  1963. for (i = 0; i < trans; i++){
  1964. carr[ofst] = coords[i];
  1965. ofst++;
  1966. }
  1967. //memcpy(&T->TexCoord[c->TexCoordEnd], coords, trans*sizeof(real));
  1968. c->TexCoordEnd += trans;
  1969. T->NextTexCoord += trans;
  1970. }
  1971. void tnsTexCoordArray3d(real *coords, int amount){
  1972. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1973. int trans = 3 * amount;
  1974. int ofst = c->TexCoordEnd;
  1975. c->UseTexCoord = 1;
  1976. c->UVDimensions = 3;
  1977. if(arrEnsureLength(&T->TexCoord, T->NextTexCoord+3*amount, &T->MaxTexCoord, sizeof(GLfloat))){
  1978. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  1979. glBufferData(GL_ARRAY_BUFFER, T->MaxTexCoord * sizeof(GLfloat), 0, GL_DYNAMIC_DRAW);
  1980. }
  1981. GLfloat *carr = T->TexCoord;
  1982. int i;
  1983. for (i = 0; i < trans; i++){ carr[ofst] = coords[i]; ofst++; }
  1984. c->TexCoordEnd += trans;
  1985. T->NextTexCoord += trans;
  1986. }
  1987. void tnsIndexArray(GLuint *index, short amount){
  1988. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  1989. //if (c->UseIndex) return;
  1990. c->UseIndex = 1;
  1991. if(arrEnsureLength(&T->Index, T->NextIndex+amount, &T->MaxIndex, sizeof(GLuint))){
  1992. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, T->IndexBufObject);
  1993. glBufferData(GL_ELEMENT_ARRAY_BUFFER, T->MaxIndex * sizeof(GLuint), 0, GL_DYNAMIC_DRAW);
  1994. }
  1995. memcpy(&T->Index[c->IndexEnd], index, amount * sizeof(GLuint));
  1996. c->IndexEnd += amount;
  1997. c->NumIndex += amount;
  1998. T->NextIndex += amount;
  1999. }
  2000. void tnsPackAs(GLenum Mode){
  2001. arrEnsureLength(&T->DrawingCommand, T->NextCommand+1, &T->MaxCommand, sizeof(tnsCommand));
  2002. tnsCommand *c = &T->DrawingCommand[T->NextCommand];
  2003. tnsCommand *nc;
  2004. T->NextCommand++;
  2005. nc = &T->DrawingCommand[T->NextCommand];
  2006. memcpy(c->UniformColor, T->StateColor, sizeof(GLfloat) * 4);
  2007. if (Mode == GL_QUAD_STRIP || Mode == GL_QUADS) Mode=GL_TRIANGLE_STRIP;
  2008. //if (Mode == GL_QUADS) Mode=GL_TRIANGLE_STRIP;
  2009. c->Mode = Mode;
  2010. c->ReplaceShader = T->StateShader;
  2011. c->ColorTexture = T->StateTexColor;
  2012. c->TextureMode = T->StateTextureMode;
  2013. c->MultiplyColor = T->StateMultiplyColor;
  2014. c->LineWidth=T->StateLineWidth;
  2015. c->PointSize=T->StatePointSize;
  2016. c->UseHalftone = T->StateUseHalftone;
  2017. memset(nc, 0, sizeof(tnsCommand));
  2018. nc->VertBegin = nc->VertEnd = c->VertEnd;
  2019. nc->NormalBegin = nc->NormalEnd = c->NormalEnd;
  2020. nc->ColorBegin = nc->ColorEnd = c->ColorEnd;
  2021. nc->TexCoordBegin = nc->TexCoordEnd = c->TexCoordEnd;
  2022. nc->IndexBegin = nc->IndexEnd = c->IndexEnd;
  2023. }
  2024. void tnsFlush(){
  2025. tnsShader *cs = T->CurrentShader;
  2026. tnsCommand *tc = &T->DrawingCommand[0];
  2027. tnsCommand *c = tc;
  2028. int PrevDimensions = 0;
  2029. int LastVertBegin = 0;
  2030. if (!c || !cs) return;
  2031. if (T->NextVert){ glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2032. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextVert * sizeof(GLfloat), T->Vert);
  2033. }
  2034. if (T->NextColor){ glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  2035. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextColor * sizeof(GLfloat), T->Color);
  2036. }
  2037. if (T->NextNormal){ glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  2038. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextNormal * sizeof(GLfloat), T->Normal);
  2039. }
  2040. if (T->NextTexCoord){ glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  2041. glBufferSubData(GL_ARRAY_BUFFER, 0, T->NextTexCoord * sizeof(GLfloat), T->TexCoord);
  2042. }
  2043. for (int i=0;i<T->NextCommand;i++){ c=&T->DrawingCommand[i];
  2044. if (c->LineWidth!=T->SetLineWidth){ glLineWidth(c->LineWidth); T->SetLineWidth=c->LineWidth; }
  2045. if (c->PointSize!=T->SetPointSize){ glLineWidth(c->PointSize); T->SetPointSize=c->PointSize; }
  2046. if (c->ReplaceShader && c->ReplaceShader != T->CurrentShader){
  2047. tnsEnableShaderv(c->ReplaceShader); cs = c->ReplaceShader;
  2048. if (!cs) continue;
  2049. }
  2050. glBindBuffer(GL_ARRAY_BUFFER, T->VertBufObject);
  2051. if (c->UseVert){
  2052. glEnableVertexAttribArray(cs->iVertex);
  2053. glVertexAttribPointer(cs->iVertex, (c->Dimensions ? c->Dimensions : PrevDimensions),
  2054. GL_FLOAT, 0, 0, c->VertBegin * sizeof(GLfloat));
  2055. LastVertBegin = c->VertBegin;
  2056. }else{
  2057. glEnableVertexAttribArray(cs->iVertex);
  2058. glVertexAttribPointer(cs->iVertex, (c->Dimensions ? c->Dimensions : PrevDimensions),
  2059. GL_FLOAT, 0, 0, LastVertBegin * sizeof(GLfloat));
  2060. }
  2061. PrevDimensions = (c->Dimensions ? c->Dimensions : PrevDimensions);
  2062. if (c->UseIndex){
  2063. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, T->IndexBufObject);
  2064. glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, c->NumIndex * sizeof(GLuint), &T->Index[c->IndexBegin]);
  2065. }
  2066. if (cs->iNormal != -1){
  2067. glBindBuffer(GL_ARRAY_BUFFER, T->NormalBufObject);
  2068. if (c->UseNormal){
  2069. glEnableVertexAttribArray(cs->iNormal); tnsUniformUseNormal(cs,1);
  2070. }
  2071. glVertexAttribPointer(cs->iNormal, 3, GL_FLOAT, 0, 0, c->NormalBegin * sizeof(GLfloat));
  2072. if (!c->UseNormal || c->Dimensions == 2){
  2073. glDisableVertexAttribArray(cs->iNormal); tnsUniformUseNormal(cs,0);
  2074. glVertexAttrib3f(cs->iNormal, 0, 0, -1);
  2075. }
  2076. }
  2077. if (cs->iColor != -1){
  2078. glBindBuffer(GL_ARRAY_BUFFER, T->ColorBufObject);
  2079. if (c->UseColor){
  2080. glEnableVertexAttribArray(cs->iColor);
  2081. glVertexAttribPointer(cs->iColor, 4, GL_FLOAT, 0, 0, c->ColorBegin * sizeof(GLfloat));
  2082. }else{
  2083. glDisableVertexAttribArray(cs->iColor);
  2084. glVertexAttrib4fv(cs->iColor, c->UniformColor);
  2085. }
  2086. }
  2087. if (cs->iUV != -1){
  2088. if (c->UseTexCoord){
  2089. glBindBuffer(GL_ARRAY_BUFFER, T->TexCoordBufObject);
  2090. if (c->UseTexCoord){ glEnableVertexAttribArray(cs->iUV);
  2091. glVertexAttribPointer(cs->iUV, c->UVDimensions, GL_FLOAT, 0, 0, c->TexCoordBegin * sizeof(GLfloat)); }
  2092. else{ glDisableVertexAttribArray(cs->iUV); }
  2093. }
  2094. }
  2095. if (c->TextureMode && c->ColorTexture && cs->iTexColor != -1){
  2096. tnsBindTexture(c->ColorTexture); tnsUniformUseTexture(cs, c->TextureMode, c->ColorTexture->Multisample);
  2097. }else{
  2098. tnsUniformUseTexture(cs, 0, 0); //tnsUnbindTexture();
  2099. }
  2100. if(cs->iMultiplyColor != -1){ tnsUniformUseMultiplyColor(cs, c->MultiplyColor); }
  2101. if(cs->iUseHalftone != -1){
  2102. tnsUniformUseHalftone(cs, c->UseHalftone);
  2103. tnsUniformHalftoneSize(cs, MAIN.ViewportHalftoneSize);
  2104. }
  2105. if (c->UseIndex){
  2106. glDrawElements(c->Mode, c->NumIndex, GL_UNSIGNED_INT, 0);
  2107. }else{
  2108. glDrawArrays(c->Mode, 0, c->NumVert);
  2109. }
  2110. }
  2111. T->NextCommand=0;
  2112. c = &T->DrawingCommand[0];
  2113. memset(c, 0, sizeof(tnsCommand));
  2114. c->ColorBegin = c->ColorEnd = T->NextColor = 0;
  2115. c->NormalBegin = c->NormalEnd = T->NextNormal = 0;
  2116. c->TexCoordBegin = c->TexCoordEnd = T->NextTexCoord = 0;
  2117. c->VertBegin = c->VertEnd = T->NextVert = 0;
  2118. c->IndexBegin = c->IndexEnd = T->NextIndex = 0;
  2119. //must --why?
  2120. //T->BindedShader = 0;
  2121. };
  2122. //============================================================================================[offscr]
  2123. const GLuint TNS_ATTACHMENT_ARRAY_NONE[] = {GL_NONE};
  2124. const GLuint TNS_ATTACHMENT_ARRAY[] = {GL_COLOR_ATTACHMENT0};
  2125. const GLuint TNS_ATTACHMENT_ARRAY_1[] = {GL_COLOR_ATTACHMENT1};
  2126. const GLuint TNS_ATTACHMENT_ARRAY_2[] = {GL_COLOR_ATTACHMENT2};
  2127. const GLuint TNS_ATTACHMENT_ARRAY_1_2[] = {GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
  2128. const GLuint TNS_ATTACHMENT_ARRAY_0_1_2[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
  2129. const GLenum TNS_WINDOW_DRAWBUFFER_ARRAY[] = {GL_BACK};
  2130. tnsOffscreen *tnsCreateOffscreenHandle(){
  2131. if(!T->CurrentContext){ printf("tnsCreateOffscreenHandle() called without GL Context. Exiting"); exit(0); }
  2132. tnsOffscreen *toff = CreateNew(tnsOffscreen); toff->FboContext=T->CurrentContext;
  2133. #ifdef _WIN32
  2134. toff->FboDC=T->CurrentDC;
  2135. #endif
  2136. #ifdef __linux__
  2137. toff->FboWindow=T->CurrentWindow;
  2138. #endif
  2139. glGenFramebuffers(1, &toff->FboHandle);
  2140. lstAppendItem(&T->Offscreens, toff);
  2141. return toff;
  2142. }
  2143. void tnsAttach2DOffscreenBuffer(tnsOffscreen *target, GLuint attatchment, tnsTexture *use){
  2144. if (!target || !use || target->FboHandle == -1 || use->GLTexHandle == -1) return;
  2145. if (attatchment >= GL_COLOR_ATTACHMENT0 && attatchment <= GL_COLOR_ATTACHMENT15){
  2146. //if (target->pColor[attatchment - GL_COLOR_ATTACHMENT0]) return;
  2147. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2148. tnsBindTexture(use);
  2149. glFramebufferTexture2D(GL_FRAMEBUFFER, attatchment, use->GLTexType, use->GLTexHandle, 0);
  2150. target->pColor[attatchment - GL_COLOR_ATTACHMENT0] = use;
  2151. tnsUnbindTexture();
  2152. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2153. }elif (attatchment == GL_DEPTH_ATTACHMENT || attatchment==GL_STENCIL_ATTACHMENT){
  2154. //if (target->pDepth) return;
  2155. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2156. tnsBindTexture(use);
  2157. glFramebufferTexture2D(GL_FRAMEBUFFER, attatchment, use->GLTexType, use->GLTexHandle, 0);
  2158. //glBindRenderbufferEXT(GL_RENDERBUFFER, use->GLTexHandle);
  2159. //glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2160. //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, use->GLTexHandle);
  2161. target->pDepth = use;
  2162. tnsUnbindTexture();
  2163. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2164. //glBindRenderbufferEXT(GL_RENDERBUFFER, 0);
  2165. //glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2166. }
  2167. GLenum result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  2168. //if (result == GL_FRAMEBUFFER_COMPLETE) { printf("Framebuffer complete!\n"); }
  2169. //else { printf("Framebuffer incomplete!\n"); }
  2170. }
  2171. void tnsDetach2DOffscreenBuffer(tnsOffscreen *target, GLuint which_attach_point){
  2172. if (which_attach_point >= GL_COLOR_ATTACHMENT0 && which_attach_point <= GL_COLOR_ATTACHMENT15){
  2173. if (target->pColor[which_attach_point - GL_COLOR_ATTACHMENT0] == 0) return;
  2174. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2175. glFramebufferTexture2D(GL_FRAMEBUFFER, which_attach_point, GL_TEXTURE_2D, 0, 0);
  2176. tnsDeleteTexture(target->pColor[which_attach_point - GL_COLOR_ATTACHMENT0]);
  2177. target->pColor[which_attach_point - GL_COLOR_ATTACHMENT0] = 0;
  2178. }elif (which_attach_point == GL_DEPTH_ATTACHMENT || which_attach_point==GL_STENCIL_ATTACHMENT){
  2179. if (target->pDepth) return;
  2180. glBindFramebuffer(GL_FRAMEBUFFER, target->FboHandle);
  2181. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
  2182. tnsDeleteTexture(target->pDepth);
  2183. target->pDepth = 0;
  2184. }
  2185. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2186. tnsUnbindTexture();
  2187. }
  2188. tnsOffscreen *tnsCreate2DOffscreen(int glInternalFormat, int w, int h, int Multisample, int WithDepth, int WithStencil){
  2189. tnsOffscreen *toff = tnsCreateOffscreenHandle();
  2190. tnsTexture *color; tnsTexture *depth;
  2191. if(glInternalFormat){
  2192. color = tnsCreate2DTexture(glInternalFormat, w, h, Multisample);
  2193. tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT0, color);
  2194. }
  2195. if(WithDepth || WithStencil){
  2196. int format=GL_DEPTH_COMPONENT;
  2197. if(WithStencil){ format=GL_DEPTH_STENCIL; }
  2198. depth = tnsCreate2DTexture(format, w, h, Multisample);
  2199. tnsAttach2DOffscreenBuffer(toff, GL_DEPTH_ATTACHMENT, depth);
  2200. if(WithStencil){ tnsAttach2DOffscreenBuffer(toff, GL_STENCIL_ATTACHMENT, depth); }
  2201. }
  2202. return toff;
  2203. }
  2204. tnsOffscreen *tnsCreateDeferredOffscreen(int w, int h, int Multisample){
  2205. tnsOffscreen *toff = tnsCreateOffscreenHandle();
  2206. tnsTexture *color,*normal,*gpos; tnsTexture *depth;
  2207. color = tnsCreate2DTexture(GL_RGBA8, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT0, color);
  2208. normal = tnsCreate2DTexture(GL_RGB8, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT1, normal);
  2209. gpos = tnsCreate2DTexture(GL_RGB32F, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_COLOR_ATTACHMENT2, gpos);
  2210. depth = tnsCreate2DTexture(GL_DEPTH_COMPONENT, w, h, Multisample); tnsAttach2DOffscreenBuffer(toff, GL_DEPTH_ATTACHMENT, depth);
  2211. return toff;
  2212. }
  2213. void tnsRecreateFBO(tnsOffscreen *off){
  2214. if(off->FboContext){
  2215. #ifdef __linux__
  2216. SYSWINDOW sw=T->CurrentWindow; SYSGLCONTEXT sc=T->CurrentContext;
  2217. tnsContextMakeCurrent(off->FboContext,off->FboWindow);
  2218. glDeleteFramebuffers(1, &off->FboHandle);
  2219. tnsContextMakeCurrent(sc,sw);
  2220. off->FboContext=sc; off->FboWindow=sw;
  2221. #endif
  2222. #ifdef _WIN32
  2223. SYSTEMDC sd=T->CurrentDC; SYSGLCONTEXT sc=T->CurrentContext;
  2224. tnsContextMakeCurrent(off->FboContext,off->FboDC);
  2225. glDeleteFramebuffers(1, &off->FboHandle);
  2226. tnsContextMakeCurrent(sc,sd);
  2227. off->FboContext=sc; off->FboDC=sd;
  2228. #endif
  2229. }
  2230. glGenFramebuffers(1, &off->FboHandle);
  2231. if(off->pColor[0]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT0, off->pColor[0]);
  2232. if(off->pColor[1]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT1, off->pColor[1]);
  2233. if(off->pColor[2]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT2, off->pColor[2]);
  2234. if(off->pColor[3]) tnsAttach2DOffscreenBuffer(off, GL_COLOR_ATTACHMENT3, off->pColor[3]);
  2235. if(off->pDepth){ tnsAttach2DOffscreenBuffer(off, GL_DEPTH_ATTACHMENT, off->pDepth);
  2236. if(off->pDepth->GLTexBitsType==GL_DEPTH_STENCIL) tnsAttach2DOffscreenBuffer(off, GL_STENCIL_ATTACHMENT, off->pDepth);
  2237. }
  2238. }
  2239. void tnsEnsureOffscreenContext(tnsOffscreen *off){
  2240. if(off->FboContext!=T->CurrentContext){ tnsRecreateFBO(off); }
  2241. }
  2242. void tnsEnsureOffscreenStatus(tnsOffscreen *off, int w, int h){
  2243. tnsTexture* t=off->pColor[0];
  2244. tnsEnsureOffscreenContext(off);
  2245. if(t->Width==w && t->Height==h) return;
  2246. t->Width = w; t->Height = h; tnsConfigure2DTexture(t);
  2247. if((t=off->pColor[1])){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2248. if((t=off->pColor[2])){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2249. if((t=off->pColor[3])){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2250. if((t=off->pDepth)){ t->Width = w; t->Height = h; tnsConfigure2DTexture(t); }
  2251. }
  2252. void tnsDelete2DOffscreen(tnsOffscreen *o){
  2253. if (!o) return;
  2254. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  2255. tnsEnsureOffscreenContext(o);
  2256. for(int i=0;i<16;i++){
  2257. if(o->pColor[i]){
  2258. tnsDetach2DOffscreenBuffer(o, GL_COLOR_ATTACHMENT0+i);
  2259. tnsDeleteTexture(o->pColor[0]);
  2260. }
  2261. }
  2262. if(o->pDepth){
  2263. tnsDetach2DOffscreenBuffer(o, GL_DEPTH_ATTACHMENT);
  2264. tnsDeleteTexture(o->pDepth);
  2265. }
  2266. glDeleteFramebuffers(1, &o->FboHandle);
  2267. lstRemoveItem(&T->Offscreens, o);
  2268. FreeMem(o);
  2269. }
  2270. void tnsDrawToOffscreen(tnsOffscreen *toff, int HowMany, GLuint *AttachmentArray){
  2271. if (!toff) return;
  2272. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, toff->FboHandle);
  2273. if(AttachmentArray==TNS_ATTACHMENT_ARRAY_NONE){glDrawBuffer(GL_NONE);}
  2274. else glDrawBuffers((HowMany ? HowMany : 1), (AttachmentArray ? AttachmentArray : TNS_ATTACHMENT_ARRAY));
  2275. T->IsOffscreen = 1;
  2276. T->BindedShader = 0;
  2277. }
  2278. void tnsDrawToOffscreenOnlyBind(tnsOffscreen *toff, int HowMany, GLuint *AttachmentArray){
  2279. if (!toff) return;
  2280. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, toff->FboHandle);
  2281. }
  2282. void tnsReadFromOffscreen(tnsOffscreen *toff){
  2283. if (!toff) return;
  2284. glBindFramebuffer(GL_READ_FRAMEBUFFER, toff->FboHandle);
  2285. }
  2286. void tnsPassColorBetweenOffscreens(tnsOffscreen *from, tnsOffscreen *to,
  2287. GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLenum FilterMode){
  2288. if (!from || !to) return;
  2289. glBlitFramebufferEXT(
  2290. srcX0, srcY0, srcX1, srcY1,
  2291. dstX0, dstY0, dstX1, dstY1,
  2292. GL_COLOR_BUFFER_BIT, FilterMode);
  2293. }
  2294. void tnsDrawToScreen(){
  2295. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  2296. //glDrawBuffer(GL_BACK); printf("%d\n", glGetError());
  2297. T->IsOffscreen = 0;
  2298. T->BindedShader = 0;
  2299. }
  2300. //===========================================================================[FONT]
  2301. tnsFontManager *FM;
  2302. void tnsSetuptnsFontManager(){
  2303. FM = CreateNew(tnsFontManager);
  2304. FM->BufferWidth = TNS_FONT_BUFFER_W_DEFAULT;
  2305. };
  2306. void tnsQuitFontManager(){
  2307. tnsInvalidateFontCache();
  2308. tnsFont*f=FM->UsingFont;
  2309. for(int i=0;i<f->NumFaces;i++){
  2310. FT_Done_Face(f->ftface[i]);
  2311. }
  2312. if(f->ftfacemono) FT_Done_Face(f->ftfacemono);
  2313. FT_Done_FreeType(f->ftlib);
  2314. free(f->characters);
  2315. free(f->monocharacters);
  2316. free(f);
  2317. FreeMem(FM);
  2318. }
  2319. int next_p2(int a){
  2320. int rval = 1;
  2321. while (rval < a)
  2322. rval <<= 1;
  2323. return rval;
  2324. }
  2325. real tnsGetMonoFontAdvance(){
  2326. return FM->UsingFont->MonoAdvance;
  2327. }
  2328. int tnsInvalidateFontCache(){
  2329. tnsFont*f=FM->UsingFont;
  2330. for(int i=0;i<TNS_UNICODE_COUNT;i++){ if(f->characters[i]){ free(f->characters[i]); f->characters[i]=0; } }
  2331. for(int i=0;i<TNS_MONO_COUNT;i++){ if(f->monocharacters[i]){ free(f->monocharacters[i]); f->monocharacters[i]=0; } }
  2332. f->CurrentX=f->CurrentY=0;
  2333. f->height = LA_RH*(MAIN.FontSize/2.0f+0.5f);
  2334. int GenHeight=LA_RH*MAIN.FontSize;
  2335. for(int i=0;i<f->NumFaces;i++){
  2336. FT_Set_Char_Size(f->ftface[i], 0, GenHeight << 6, 96, 96);
  2337. FT_Glyph glyph; int half_adv=0;
  2338. if(!FT_Get_Advance(f->ftface[i],'a',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &half_adv)){
  2339. if (FT_Load_Char(f->ftface[i], 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2340. FT_Get_Glyph(f->ftface[i]->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2341. f->MonoAdvance=(real)f->ftface[i]->glyph->advance.x/64.0;
  2342. if(glyph) FT_Done_Glyph(glyph);
  2343. }
  2344. }
  2345. if(f->ftfacemono){
  2346. FT_Set_Char_Size(f->ftfacemono, 0, (GenHeight << 6)*f->MonoScale, 96, 96); FT_Glyph glyph;
  2347. if (FT_Load_Char(f->ftfacemono, 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2348. FT_Get_Glyph(f->ftfacemono->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2349. f->MonoAdvance=(real)f->ftfacemono->glyph->advance.x/64.0;
  2350. if(glyph) FT_Done_Glyph(glyph);
  2351. }
  2352. if(glClearTexImage) glClearTexImage(f->TexBuffer.GLTexHandle, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  2353. }
  2354. tnsFontSingleCharacter *tfntFetchCharTextureIDW(uint32_t ch, int UseMono);
  2355. #ifndef LAGUI_FONT_CUSTOM_PATH
  2356. #define LAGUI_FONT_CUSTOM_PATH "/usr/share/fonts/opentype/noto/"
  2357. #endif
  2358. const char* TNS_FONT_CUSTOM=LAGUI_FONT_CUSTOM_PATH;
  2359. const char* TNS_FONT_LOAD_OPTIONS[9]={"","fonts/","lagui/fonts/","../","../fonts/","../lagui/fonts/","../../","../../fonts/","../../lagui/fonts/"};
  2360. const char* TNS_FONT_LOAD_OPTIONS_FROM_HOME[2]={".local/share/fonts/lagui/",".local/share/fonts/"};
  2361. int tnsLoadSystemFontMono(char* from, char* mono){
  2362. char buf[1024]; if(!FM->UsingFont || !mono || !mono[0]) return 0;
  2363. tnsFont *f=FM->UsingFont;
  2364. int GenHeight=LA_RH*MAIN.FontSize;
  2365. int full_adv=0,half_adv=0;
  2366. for(int i=0;i<f->NumFaces;i++){
  2367. if(!FT_Get_Advance(f->ftface[i],U'我',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &full_adv)) break;
  2368. }
  2369. for(int i=-2;i<11;i++){
  2370. char* option;
  2371. if(i==-2){ sprintf(buf,"%s%s%s",TNS_FONT_CUSTOM,TNS_FONT_CUSTOM[strlen(TNS_FONT_CUSTOM)-1]=='/'?"":"/",mono); }
  2372. elif(i<9){ option=(i==-1)?from:TNS_FONT_LOAD_OPTIONS[i]; sprintf(buf,"%s%s%s",MAIN.WorkingDirectory->Ptr,option,mono); }
  2373. else{ option=TNS_FONT_LOAD_OPTIONS_FROM_HOME[i-9]; sprintf(buf,"%s/%s%s",getenv("HOME"),option,mono); }
  2374. if (FT_New_Face(f->ftlib, buf, 0, &f->ftfacemono)) continue;
  2375. FT_Select_Charmap(f->ftfacemono, FT_ENCODING_UNICODE);
  2376. FT_Set_Char_Size(f->ftfacemono, 0, GenHeight << 6, 96, 96);
  2377. logPrint("Loaded monospace font: %s\n",buf);
  2378. if(!FT_Get_Advance(f->ftfacemono,'a',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &half_adv)){
  2379. f->MonoScale=(real)full_adv/(half_adv*2);
  2380. FT_Set_Char_Size(f->ftfacemono, 0, (GenHeight << 6)*f->MonoScale, 96, 96);
  2381. logPrint("Monospace font scale: %.2f\n",f->MonoScale); FT_Glyph glyph;
  2382. if (FT_Load_Char(f->ftfacemono, 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2383. FT_Get_Glyph(f->ftfacemono->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2384. f->MonoAdvance=(real)f->ftfacemono->glyph->advance.x/64.0;
  2385. if(glyph) FT_Done_Glyph(glyph);
  2386. }
  2387. return 1;
  2388. }
  2389. return 0;
  2390. };
  2391. int tnsLoadSystemFont(char* from, char* name){
  2392. char buf[1024];
  2393. tnsFont *f=FM->UsingFont; if(!f){
  2394. f = CreateNew(tnsFont);
  2395. f->characters=calloc(1, sizeof(tnsFontSingleCharacter*)*TNS_UNICODE_COUNT);
  2396. f->monocharacters=calloc(1, sizeof(tnsFontSingleCharacter*)*TNS_MONO_COUNT);
  2397. f->height = LA_RH*(MAIN.FontSize/2.0f+0.5f);
  2398. tnsInit2DTexture(&f->TexBuffer, GL_RED, FM->BufferWidth, FM->BufferWidth, 0);
  2399. lstAppendItem(&FM->Fonts, f); FM->UsingFont=f;
  2400. if (FT_Init_FreeType(&f->ftlib)) SEND_PANIC_ERROR("Freetype Init Failed!");
  2401. logPrintNew("Loading fonts...\n");
  2402. }
  2403. int GenHeight=LA_RH*MAIN.FontSize;
  2404. for(int i=-2;i<11;i++){
  2405. char* option;
  2406. if(i==-2){ sprintf(buf,"%s%s%s",TNS_FONT_CUSTOM,TNS_FONT_CUSTOM[strlen(TNS_FONT_CUSTOM)-1]=='/'?"":"/",name); }
  2407. elif(i<9){ option=(i==-1)?from:TNS_FONT_LOAD_OPTIONS[i]; sprintf(buf,"%s%s%s",MAIN.WorkingDirectory->Ptr,option,name); }
  2408. else{ option=TNS_FONT_LOAD_OPTIONS_FROM_HOME[i-9]; sprintf(buf,"%s/%s%s",getenv("HOME"),option,name); }
  2409. FT_Face face; FT_Long i,num_faces; FT_Open_Args args; args.flags=FT_OPEN_PATHNAME; args.pathname=buf;
  2410. if(FT_Open_Face(f->ftlib, &args, -1, &face )) continue;
  2411. num_faces = face->num_faces; FT_Done_Face(face); int found=0;
  2412. for(int fa=0;fa<num_faces;fa++){
  2413. if(FT_Open_Face(f->ftlib,&args,fa,&face)){ continue; }
  2414. if(strstr(face->family_name,"SC")){ found=1; break; }
  2415. FT_Done_Face(face);
  2416. }
  2417. if(found){ f->ftface[f->NumFaces]=face; }else{ if (FT_New_Face(f->ftlib, buf, 0, &f->ftface[f->NumFaces])) continue; }
  2418. FT_Select_Charmap(f->ftface[f->NumFaces], FT_ENCODING_UNICODE);
  2419. FT_Set_Char_Size(f->ftface[f->NumFaces], 0, GenHeight << 6, 96, 96);
  2420. f->NumFaces++; FT_Glyph glyph; int half_adv=0;
  2421. if(!f->MonoAdvance && !FT_Get_Advance(f->ftface[f->NumFaces],'a',FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP, &half_adv)){
  2422. FT_Set_Char_Size(f->ftface[f->NumFaces], 0, (GenHeight << 6)*f->MonoScale, 96, 96);
  2423. if (FT_Load_Char(f->ftface[f->NumFaces], 'a', FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)||
  2424. FT_Get_Glyph(f->ftface[f->NumFaces]->glyph, &glyph)){ SEND_PANIC_ERROR("Monospace font doesn't contain character 'a'"); }
  2425. f->MonoAdvance=(real)f->ftface[f->NumFaces]->glyph->advance.x/64.0;
  2426. if(glyph) FT_Done_Glyph(glyph);
  2427. }
  2428. logPrint("Loaded font: %s\n",buf);
  2429. return 1;
  2430. }
  2431. return 0;
  2432. };
  2433. int tfntBufferWidthEnough(int total_width, int current_width, int this_width){
  2434. return (current_width + this_width +1 < total_width);
  2435. }
  2436. void tfntResizeFontTexture(tnsFont* f, int size){
  2437. FM->BufferWidth=size;
  2438. f->TexBuffer.Width=f->TexBuffer.Height=FM->BufferWidth;
  2439. tnsConfigure2DTexture(&f->TexBuffer);
  2440. }
  2441. void tfntApplyCharacterBufferOffset(tnsFont *f, tnsFontSingleCharacter *fsc){
  2442. if (!tfntBufferWidthEnough(FM->BufferWidth, f->CurrentX, fsc->width)){
  2443. f->CurrentY += (f->height+1);
  2444. f->CurrentX = 0;
  2445. }
  2446. fsc->bufferx = f->CurrentX;
  2447. fsc->buffery = f->CurrentY;
  2448. f->CurrentX += (fsc->width+1);
  2449. }
  2450. tnsFontSingleCharacter *tfntFetchCharTextureIDW(uint32_t ch, int UseMono){
  2451. GLuint revel = 0;
  2452. tnsFont *f = FM->UsingFont;
  2453. tnsFontSingleCharacter **use_fsc=UseMono?f->monocharacters:f->characters, *fsc = 0;
  2454. FT_Glyph glyph = 0;
  2455. FT_BitmapGlyph bitmap_glyph;
  2456. FT_Bitmap bm;
  2457. FT_Face face;
  2458. int w, h, i, j;
  2459. GLubyte *buf = 0;
  2460. if (!f) return 0;
  2461. if(ch>TNS_MONO_COUNT){ UseMono=0; use_fsc=f->characters; }
  2462. if(ch>TNS_UNICODE_COUNT){ return 0; }
  2463. fsc = use_fsc[ch];
  2464. if(!fsc){ fsc=use_fsc[ch]=calloc(1,sizeof(tnsFontSingleCharacter)); }
  2465. if (revel = fsc->Generated) return fsc;
  2466. if(UseMono && f->ftfacemono){
  2467. face = f->ftfacemono;
  2468. if(!FT_Get_Char_Index(face,ch)){return 0;}
  2469. if (FT_Load_Char(face, ch, FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)){ return 0; }
  2470. if (FT_Get_Glyph(face->glyph, &glyph)){ return 0; }
  2471. }else{
  2472. for(int i=0;i<f->NumFaces;i++){
  2473. if(!f->ftface[i]){continue;}
  2474. face = f->ftface[i];
  2475. if(!FT_Get_Char_Index(face,ch)){continue;}
  2476. if (FT_Load_Char(face, ch, FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP)){ continue; }
  2477. if (FT_Get_Glyph(face->glyph, &glyph)){ continue; }
  2478. break;
  2479. }
  2480. if(!glyph){ return 0; }
  2481. }
  2482. FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL);
  2483. FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
  2484. bitmap_glyph = glyph;
  2485. bm = bitmap_glyph->bitmap;
  2486. w = bm.width;
  2487. h = bm.rows;
  2488. fsc->width = w;
  2489. fsc->height = h;
  2490. fsc->advx = (real)face->glyph->advance.x / 64.0f;
  2491. fsc->advy = face->size->metrics.y_ppem;
  2492. fsc->deltax = bitmap_glyph->left;
  2493. fsc->deltay = bitmap_glyph->top - h;
  2494. tfntApplyCharacterBufferOffset(f, fsc);
  2495. if(fsc->buffery+h>=FM->BufferWidth){
  2496. tfntResizeFontTexture(f,FM->BufferWidth*2); tnsInvalidateFontCache();
  2497. FreeMem(buf); FT_Done_Glyph(glyph);
  2498. return tfntFetchCharTextureIDW(ch,UseMono);
  2499. }
  2500. tnsBindTexture(&f->TexBuffer);
  2501. //glBindTexture(GL_TEXTURE_2D, f->TexBuffer.GLTexHandle);
  2502. buf = CreateNewBuffer(GLubyte, w * h);
  2503. for (j = 0; j < h; j++){
  2504. for (i = 0; i < w; i++){
  2505. char _vl = bm.buffer[i + w * j];
  2506. buf[i + (h - j - 1) * w] = _vl;
  2507. }
  2508. }
  2509. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  2510. glTexSubImage2D(GL_TEXTURE_2D, 0, fsc->bufferx, fsc->buffery, w, h, GL_RED, GL_UNSIGNED_BYTE, buf);
  2511. FreeMem(buf);
  2512. FT_Done_Glyph(glyph);
  2513. fsc->Generated = 1;
  2514. return fsc;
  2515. }
  2516. tnsFontSingleCharacter *tfntFetchCharacterW(uint32_t ch, int UseMono){
  2517. tnsFontSingleCharacter* fsc = tfntFetchCharTextureIDW(ch, UseMono);
  2518. if(fsc) return fsc;
  2519. return tfntFetchCharTextureIDW('?', UseMono);
  2520. }
  2521. int CMP_NAME_IsThisFont(tnsFont *enumed, char *name){
  2522. return (!strcmp(enumed->fontName, name));
  2523. };
  2524. int tnsStringGetDimension(char* content, uint32_t* contentU, int Count, int WLimit, int* Rows, int UseMono){
  2525. if((!MAIN.CurrentWindow)||(!MAIN.CurrentWindow->win)) return 0;
  2526. real sx = 0; int sy = FM->UsingFont->height; real MA=FM->UsingFont->MonoAdvance;
  2527. int i, rows=1, advance=1;
  2528. int C = 0;
  2529. int len = contentU?strlenU(contentU):(content?strlen(content):0);
  2530. char hb;
  2531. int RestoreI;
  2532. int MaxSX=0;
  2533. if(!WLimit){WLimit=INT_MAX;}
  2534. int UC=1;
  2535. for (i = 0; i < len && UC; i+=advance){
  2536. UC = contentU?contentU[i]:laToUnicode(&content[i], &advance);
  2537. tnsFontSingleCharacter *fsc;
  2538. if (UC == U'\n'){
  2539. if(sx>MaxSX) MaxSX=sx;
  2540. sx = 0; sy += LA_RH; rows++;
  2541. continue;
  2542. }else{
  2543. fsc = tfntFetchCharacterW(UC, UseMono);
  2544. real dx=fsc->advx; if(UseMono){ dx/=MA; if(dx<1.01) dx=1; if(dx>1.01)dx=2; dx*=MA; }
  2545. if(sx+dx > WLimit){ sx = 0; sy += LA_RH; rows++; }
  2546. sx += dx;
  2547. C += 1;
  2548. if (Count && C == Count) break;
  2549. }
  2550. }
  2551. if(sx==0 && rows>1){rows--;}
  2552. if(sx>MaxSX) MaxSX=sx;
  2553. if(Rows) (*Rows)=rows;
  2554. return MaxSX+1;
  2555. }
  2556. int tnsStringGetWidth(char *content, int Count, int UseMono){
  2557. return tnsStringGetDimension(content, 0, Count, 0, 0, UseMono);
  2558. }
  2559. int tnsStringGetWidthU(uint32_t *contentU, int Count, int UseMono){
  2560. return tnsStringGetDimension(0, contentU, Count, 0, 0, UseMono);
  2561. }
  2562. int tnsDrawLCD7_ProgressSystem(real x, real y, real Percent){
  2563. real hgap=LA_RH/15; real vgap=LA_RH/5;
  2564. real MA=FM->UsingFont->MonoAdvance;
  2565. real w=MA-hgap*2, h=LA_RH-vgap*2; y+=vgap; x+=hgap-MA; real shear=h/12;
  2566. TNS_CLAMP(Percent,0,1);
  2567. char str[10]; sprintf(str,"%d",(int)(Percent*100)); int len=strlen(str);
  2568. for(int i=len-1;i>=0;i--){
  2569. int uc=str[i];
  2570. if(uc>='0' && uc<='9'){ uc-='0'; }
  2571. else { continue; }
  2572. for(int i=0;i<7;i++){
  2573. if(TNS_LCD_MAP_7[uc][i]){
  2574. real* seg=TNS_LCD_SEG_7[i];
  2575. real s1=tnsInterpolate(shear,-shear,seg[1]); real s2=tnsInterpolate(shear,-shear,seg[3]);
  2576. #ifdef __linux__
  2577. XDrawLine(MAIN.dpy,MAIN.Progress.w,MAIN.Progress.gc,
  2578. tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]),
  2579. tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2580. #endif
  2581. #ifdef _WIN32
  2582. MoveToEx(MAIN.Progress.hdc,tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]),0);
  2583. LineTo(MAIN.Progress.hdc,tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2584. #endif
  2585. }
  2586. }
  2587. x-=MA;
  2588. }
  2589. return 1;
  2590. return 0;
  2591. }
  2592. int tnsMakeLCD7(real x, real y, real w, real h, real shear, int ch){
  2593. int uc=ch;
  2594. if(ch>='0' && ch<='9'){ uc-='0'; }
  2595. else {return 0;}
  2596. for(int i=0;i<7;i++){
  2597. if(TNS_LCD_MAP_7[uc][i]){
  2598. real* seg=TNS_LCD_SEG_7[i];
  2599. real s1=tnsInterpolate(shear,-shear,seg[1]); real s2=tnsInterpolate(shear,-shear,seg[3]);
  2600. tnsVertex2d(tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]));
  2601. tnsVertex2d(tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2602. }
  2603. }
  2604. return 1;
  2605. }
  2606. int tnsMakeLCD16(real x, real y, real w, real h, real shear, int ch){
  2607. int uc=ch;
  2608. if(ch>='0' && ch<='9'){ uc-='0'; }
  2609. elif(ch>='A' && ch<='Z'){ uc-='A'; uc+=10; }
  2610. elif(ch>='a' && ch<='z'){ uc-='a'; uc+=(10+26); }
  2611. else {return 0;}
  2612. for(int i=0;i<16;i++){
  2613. if(TNS_LCD_MAP_16[uc][i]){
  2614. real* seg=TNS_LCD_SEG_16[i];
  2615. real s1=tnsInterpolate(shear,-shear,seg[1]); real s2=tnsInterpolate(shear,-shear,seg[3]);
  2616. tnsVertex2d(tnsInterpolate(x+s1,x+w+s1,seg[0]),tnsInterpolate(y,y+h,seg[1]));
  2617. tnsVertex2d(tnsInterpolate(x+s2,x+w+s2,seg[2]),tnsInterpolate(y,y+h,seg[3]));
  2618. }
  2619. }
  2620. return 1;
  2621. }
  2622. void tnsDrawStringLCD(char *content, uint32_t* contentU, real Color[4], int L, int R, int T, int Flags, real Scale){
  2623. if(Scale<1e-5) return;
  2624. real MA=FM->UsingFont->MonoAdvance;
  2625. real sx = L; int sy = T; real dx=MA; real hgap=LA_RH/15; real vgap=LA_RH/5;
  2626. int i,advance=1;
  2627. int len = contentU?strlenU(contentU):strlen(content);
  2628. int RevY=(Flags&LA_TEXT_REVERT_Y); int TH=LA_RH-vgap*2; real shear=TH/12;
  2629. if(RevY){ TH*=-1; vgap*=-1; } TH*=Scale;dx*=Scale;hgap*=Scale;vgap*=Scale;shear*=Scale;
  2630. int OneLine=(Flags&LA_TEXT_ONE_LINE);
  2631. int Use16=(Flags&LA_TEXT_LCD_16);
  2632. tnsFlush();
  2633. tnsUseNoTexture();
  2634. int any=0, UC=1; int BreakNow=0;
  2635. for (i = 0; i < len && UC; i+=advance){
  2636. UC = contentU?contentU[i]:laToUnicode(&content[i], &advance);
  2637. if (UC == U'\n'){ if(!OneLine){sx = L; sy += LA_RH; continue;}else{ UC=' '; } }
  2638. if (sx + dx > R+1){
  2639. if(Flags&LA_TEXT_LINE_WRAP){ sx=L; sy+=LA_RH; }else{ break; }
  2640. }
  2641. if(Use16){
  2642. if(tnsMakeLCD16(sx+hgap, sy+vgap, dx-hgap*2, TH, shear, UC)) any=1;
  2643. }else{
  2644. if(tnsMakeLCD7(sx+hgap, sy+vgap, dx-hgap*2, TH, shear, UC)) any=1;
  2645. }
  2646. sx += dx;
  2647. if(BreakNow){ break; }
  2648. }
  2649. if(any){ tnsColor4dv(Color); tnsPackAs(GL_LINES); }
  2650. }
  2651. void tnsDrawStringM(char *content, uint32_t* contentU, real Color[4], int L, int R, int T, int Flags){
  2652. if(Flags&(LA_TEXT_LCD_16|LA_TEXT_LCD_7)){
  2653. tnsDrawStringLCD(content,contentU,Color,L,R,T,Flags,1.0); return;
  2654. }
  2655. real sx = L; int sy = (LA_RH!=LA_RH0)?(((((real)FM->UsingFont->height/LA_RH0-0.5)/MAIN.UiScale)+0.5)*LA_RH + T):(FM->UsingFont->height+T);
  2656. real MA=FM->UsingFont->MonoAdvance;
  2657. int i,advance=1;
  2658. int len = contentU?strlenU(contentU):(content?strlen(content):0); if(!len) return;
  2659. real xo, yo, xl, yl;
  2660. real TexCoord[12];
  2661. real VertArr[12];
  2662. int total_width = 0;
  2663. tnsFont *f = FM->UsingFont;
  2664. int FscHeight, RestoreI;
  2665. int RevY=(Flags&LA_TEXT_REVERT_Y);
  2666. int UseMono=(Flags&LA_TEXT_MONO);
  2667. int OneLine=(Flags&LA_TEXT_ONE_LINE);
  2668. if(Color) tnsColor4dv(Color);
  2669. int any=0, UC=1; int BreakNow=0;
  2670. for (i = 0; i < len && UC; i+=advance){
  2671. UC = contentU?contentU[i]:laToUnicode(&content[i], &advance);
  2672. tnsFontSingleCharacter *fsc;
  2673. real cx, cy;
  2674. if (UC == U'\n'){ if(!OneLine){sx = L; sy += LA_RH; continue;}else{ UC=' '; } }
  2675. fsc = tfntFetchCharacterW(UC, Flags&LA_TEXT_MONO);
  2676. real dx=fsc->advx; if(UseMono){ dx/=MA; if(dx<1.01) dx=1; if(dx>1.01)dx=2; dx*=MA; }
  2677. if (sx + dx > R+1){
  2678. if(Flags&LA_TEXT_LINE_WRAP){
  2679. sx=L; sy+=LA_RH;
  2680. }else{
  2681. if(Flags&LA_TEXT_OVERFLOW_ARROW){ fsc = tfntFetchCharacterW(U'▷', 0); sx=R-fsc->advx; BreakNow=1; }
  2682. else break;
  2683. }
  2684. }
  2685. cx = sx + fsc->deltax;
  2686. cy = sy - fsc->deltay;
  2687. xo = (real)fsc->bufferx / (real)FM->BufferWidth;
  2688. yo = (real)fsc->buffery / (real)FM->BufferWidth;
  2689. xl = (real)(fsc->bufferx + fsc->width) / (real)FM->BufferWidth;
  2690. yl = (real)(fsc->buffery + fsc->height) / (real)FM->BufferWidth;
  2691. tnsMakeQuadT2d(TexCoord, xo, yl, xo, yo, xl, yl, xl, yo);
  2692. if (RevY) tnsMakeQuadT2d(VertArr,
  2693. cx, 2 * T - cy + fsc->height,
  2694. cx, 2 * T - cy,
  2695. cx + fsc->width, 2 * T - cy + fsc->height,
  2696. cx + fsc->width, 2 * T - cy);
  2697. else tnsMakeQuadT2d(VertArr,
  2698. cx, +cy - fsc->height,
  2699. cx, +cy,
  2700. cx + fsc->width, +cy - fsc->height,
  2701. cx + fsc->width, +cy);
  2702. tnsUseMaskTexture(&f->TexBuffer);
  2703. tnsVertexArray2d(VertArr, 6);
  2704. tnsTexCoordArray2d(TexCoord, 6);
  2705. any=1;
  2706. sx += dx;
  2707. if(BreakNow){ break; }
  2708. }
  2709. if(any) tnsPackAs(GL_TRIANGLES);
  2710. }
  2711. void tnsDrawStringAutoM(char *content, uint32_t* contentU, real Color[4], int L, int R, int T, int Flags){
  2712. int LL;
  2713. int al = Flags&LA_TEXT_ALIGN;
  2714. if (!content && !contentU) return;
  2715. switch (al){
  2716. case LA_TEXT_ALIGN_AUTO:
  2717. case LA_TEXT_ALIGN_CENTER: LL = L+(R-L-tnsStringGetDimension(content, contentU, 0, 0, 0, Flags&LA_TEXT_MONO)) / 2; if(LL<L) LL=L; break;
  2718. default:
  2719. case LA_TEXT_ALIGN_LEFT: LL = L; break;
  2720. case LA_TEXT_ALIGN_RIGHT: LL = R-(tnsStringGetDimension(content, contentU, 0, 0, 0, Flags&LA_TEXT_MONO)); if(LL<L) LL=L; break;
  2721. }
  2722. tnsDrawStringM(content, contentU, Color, LL, R, T, Flags);
  2723. }
  2724. void tnsDrawStringAuto(char *content, real Color[4], int L, int R, int T, int Flags){
  2725. tnsDrawStringAutoM(content,0,Color,L,R,T,Flags);
  2726. }
  2727. void tnsDrawStringWithPriority(char *Label, char *MajorContent, real Color[4], int TextAlign, int L, int R, int T, int Flags){
  2728. int W = R - L;
  2729. int Str1W = tnsStringGetWidth(Label, 0, Flags&LA_TEXT_MONO);
  2730. int Str2W = tnsStringGetWidth(MajorContent, 0, Flags&LA_TEXT_MONO);
  2731. if (Str1W + Str2W > W){
  2732. if (Str2W < W){
  2733. tnsDrawStringM(MajorContent, 0, Color, R - Str2W, R, T, Flags);
  2734. tnsDrawStringM(Label, 0, Color, L, R - Str2W, T, Flags);
  2735. }else
  2736. tnsDrawStringM(MajorContent, 0, Color, L, R, T, Flags);
  2737. }else{
  2738. int LL = L, ML;
  2739. switch (Flags&LA_TEXT_ALIGN){
  2740. case LA_TEXT_ALIGN_CENTER:
  2741. ML = L + Str1W + (W - (Str1W + Str2W)) / 2;
  2742. break;
  2743. case LA_TEXT_ALIGN_LEFT:
  2744. ML = L + Str1W;
  2745. break;
  2746. default:
  2747. case LA_TEXT_ALIGN_AUTO:
  2748. case LA_TEXT_ALIGN_RIGHT:
  2749. ML = R - Str2W;
  2750. break;
  2751. }
  2752. tnsDrawStringM(Label, 0, Color, LL, R, T, Flags);
  2753. tnsDrawStringM(MajorContent, 0, Color, ML, R, T, Flags);
  2754. }
  2755. }
  2756. void tnsDrawIcon(uint32_t ID, real Color[4], int L,int R, int T, int Flags){
  2757. char buf[5]={0}; char* next; laToUTF8(ID,buf,&next);
  2758. tnsDrawStringAuto(buf, Color, L,R,T,Flags);
  2759. }
  2760. //=====================================================================================[Object]
  2761. tnsObject *tnsFindObject(char *Name, tnsObject *FromObj){
  2762. tnsObject *io; tnsObject *ro;
  2763. laListHandle* l=FromObj?(&FromObj->ChildObjects):(&T->World->AllObjects);
  2764. for (laListItemPointer*lip=l->pFirst;lip;lip=lip->pNext){
  2765. io=((l==&T->World->AllObjects)?lip:lip->p); if (strSame(io->Name->Ptr, Name)){ return io; }
  2766. if (ro = tnsFindObject(Name, io)) return ro;
  2767. }
  2768. return 0;
  2769. }
  2770. void tnsExtractDeltaTransformValue(tnsObject *o){
  2771. if (!o) return;
  2772. tnsExtractLocation44d(o->DeltaTransform, o->DLocation);
  2773. tnsExtractXYZEuler44d(o->DeltaTransform, o->DRotation);
  2774. tnsExtractScale44d(o->DeltaTransform, o->DScale);
  2775. }
  2776. void tnsExtractSelfTransformValue(tnsObject *o){
  2777. if (!o) return;
  2778. tnsExtractLocation44d(o->SelfTransform, o->Location);
  2779. tnsExtractXYZEuler44d(o->SelfTransform, o->Rotation);
  2780. tnsExtractScale44d(o->SelfTransform, o->Scale);
  2781. }
  2782. void tnsExtractGlobalTransformValue(tnsObject *o){
  2783. if (!o) return;
  2784. tnsExtractLocation44d(o->GlobalTransform, o->GLocation);
  2785. tnsExtractXYZEuler44d(o->GlobalTransform, o->GRotation);
  2786. tnsExtractScale44d(o->GlobalTransform, o->GScale);
  2787. }
  2788. void tnsCopyGlobalTransform(tnsObject *to, tnsObject *from){
  2789. memcpy(to->GlobalTransform, from->GlobalTransform, sizeof(tnsMatrix44d));
  2790. memcpy(to->GLocation, from->GLocation, sizeof(tnsVector3d));
  2791. memcpy(to->GRotation, from->GRotation, sizeof(tnsVector3d));
  2792. memcpy(to->GScale, from->GScale, sizeof(tnsVector3d));
  2793. tnsGlobalTransformValueChanged(to);
  2794. }
  2795. void tnsSelfMatrixChanged(tnsObject* o, int ApplyToChild){
  2796. tnsMatrix44d mix;
  2797. if (!o->ParentObject){
  2798. tnsMultiply44d(mix, o->SelfTransform, o->DeltaTransform);
  2799. memcpy(o->GlobalTransform, mix, sizeof(tnsMatrix44d));
  2800. }
  2801. else{
  2802. tnsMultiply44d(mix, o->ParentObject->GlobalTransform, o->SelfTransform);
  2803. tnsMultiply44d(o->GlobalTransform, mix, o->DeltaTransform);
  2804. }
  2805. tnsExtractDeltaTransformValue(o);
  2806. tnsExtractSelfTransformValue(o);
  2807. tnsExtractGlobalTransformValue(o); tnsInvalidateEvaluation(o);
  2808. if(ApplyToChild) for (laListItemPointer* li=o->ChildObjects.pFirst;li;li=li->pNext){ tnsSelfMatrixChanged(li->p,1); }
  2809. }
  2810. void tnsGlobalMatrixChanged(tnsObject* o, int ApplyToChild){
  2811. tnsMatrix44d self,invd;
  2812. if (!o->ParentObject){ memcpy(self, o->GlobalTransform, sizeof(tnsMatrix44d)); }
  2813. else{ tnsMatrix44d inv;
  2814. tnsInverse44d(inv, o->ParentObject->GlobalTransform);
  2815. tnsMultiply44d(self, inv, o->GlobalTransform); }
  2816. tnsInverse44d(invd, o->DeltaTransform);
  2817. tnsMultiply44d(o->SelfTransform, self, invd);
  2818. tnsExtractSelfTransformValue(o);
  2819. tnsExtractGlobalTransformValue(o); tnsInvalidateEvaluation(o);
  2820. if(ApplyToChild) for (laListItemPointer* li=o->ChildObjects.pFirst;li;li=li->pNext){ tnsSelfMatrixChanged(li->p,1); }
  2821. }
  2822. void tnsGlobalMatrixChangedForDelta(tnsObject* o, int ApplyToChild){
  2823. tnsMatrix44d invs, invp, tmp;
  2824. if (!o->ParentObject){ tnsLoadIdentity44d(invp); }
  2825. else{ tnsInverse44d(invp, o->ParentObject->GlobalTransform); }
  2826. tnsInverse44d(invs, o->SelfTransform);
  2827. tnsMultiply44d(tmp, invs, invp);
  2828. tnsMultiply44d(o->DeltaTransform, tmp, o->GlobalTransform);
  2829. tnsExtractDeltaTransformValue(o);
  2830. //tnsExtractSelfTransformValue(o);
  2831. tnsExtractGlobalTransformValue(o); tnsInvalidateEvaluation(o);
  2832. if(ApplyToChild) for (laListItemPointer* li=o->ChildObjects.pFirst;li;li=li->pNext){ tnsSelfMatrixChanged(li->p,1); }
  2833. }
  2834. void tnsSelfTransformValueChanged(tnsObject* o){
  2835. tnsMatrix44d Trans, Rot1, Rot2, Rot3, Scale, Res1, Res2;
  2836. tnsLoadIdentity44d(o->SelfTransform);
  2837. tnsMakeTranslationMatrix44d(Trans, LA_COLOR3(o->Location));
  2838. if(o->Scale[0]<1e-5){ o->Scale[0]=1e-5; }
  2839. if(o->Scale[1]<1e-5){ o->Scale[1]=1e-5; }
  2840. if(o->Scale[2]<1e-5){ o->Scale[2]=1e-5; }
  2841. tnsMakeScaleMatrix44d(Scale, LA_COLOR3(o->Scale));
  2842. tnsMakeRotationXMatrix44d(Rot1, o->Rotation[0]);
  2843. tnsMakeRotationYMatrix44d(Rot2, o->Rotation[1]);
  2844. tnsMakeRotationZMatrix44d(Rot3, o->Rotation[2]);
  2845. switch (o->RotationMode){
  2846. case TNS_ROTATION_ZYX_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot3); break;
  2847. case TNS_ROTATION_XZY_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot2); break;
  2848. case TNS_ROTATION_YXZ_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot3); break;
  2849. case TNS_ROTATION_YZX_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot1); break;
  2850. case TNS_ROTATION_ZXY_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot2); break;
  2851. case TNS_ROTATION_XYZ_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot1); break;
  2852. }
  2853. tnsMultiply44d(o->SelfTransform, Res1, Scale);
  2854. tnsSelfMatrixChanged(o,1);
  2855. }
  2856. void tnsDeltaTransformValueChanged(tnsObject* o){
  2857. tnsMatrix44d Trans, Rot1, Rot2, Rot3, Scale, Res1, Res2;
  2858. tnsLoadIdentity44d(o->DeltaTransform);
  2859. tnsMakeTranslationMatrix44d(Trans, LA_COLOR3(o->DLocation));
  2860. tnsMakeScaleMatrix44d(Scale, LA_COLOR3(o->DScale));
  2861. tnsMakeRotationXMatrix44d(Rot1, o->DRotation[0]);
  2862. tnsMakeRotationYMatrix44d(Rot2, o->DRotation[1]);
  2863. tnsMakeRotationZMatrix44d(Rot3, o->DRotation[2]);
  2864. switch (o->RotationMode){
  2865. case TNS_ROTATION_ZYX_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot3); break;
  2866. case TNS_ROTATION_XZY_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot2); break;
  2867. case TNS_ROTATION_YXZ_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot3); break;
  2868. case TNS_ROTATION_YZX_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot1); break;
  2869. case TNS_ROTATION_ZXY_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot2); break;
  2870. case TNS_ROTATION_XYZ_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot1); break;
  2871. }
  2872. tnsMultiply44d(o->DeltaTransform, Res1, Scale);
  2873. tnsSelfMatrixChanged(o,1);
  2874. }
  2875. void tnsGlobalTransformValueChanged(tnsObject* o){
  2876. tnsMatrix44d Trans, Rot1, Rot2, Rot3, Scale, Res1, Res2;
  2877. tnsLoadIdentity44d(o->GlobalTransform);
  2878. tnsMakeTranslationMatrix44d(Trans, LA_COLOR3(o->GLocation));
  2879. tnsMakeScaleMatrix44d(Scale, LA_COLOR3(o->GScale));
  2880. tnsMakeRotationXMatrix44d(Rot1, o->GRotation[0]);
  2881. tnsMakeRotationYMatrix44d(Rot2, o->GRotation[1]);
  2882. tnsMakeRotationZMatrix44d(Rot3, o->GRotation[2]);
  2883. switch (o->RotationMode){
  2884. case TNS_ROTATION_ZYX_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot3); break;
  2885. case TNS_ROTATION_XZY_EULER: tnsMultiply44d(Res1, Trans, Rot1); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot2); break;
  2886. case TNS_ROTATION_YXZ_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot3); break;
  2887. case TNS_ROTATION_YZX_EULER: tnsMultiply44d(Res1, Trans, Rot2); tnsMultiply44d(Res2, Res1, Rot3); tnsMultiply44d(Res1, Res2, Rot1); break;
  2888. case TNS_ROTATION_ZXY_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot1); tnsMultiply44d(Res1, Res2, Rot2); break;
  2889. case TNS_ROTATION_XYZ_EULER: tnsMultiply44d(Res1, Trans, Rot3); tnsMultiply44d(Res2, Res1, Rot2); tnsMultiply44d(Res1, Res2, Rot1); break;
  2890. }
  2891. tnsMultiply44d(o->GlobalTransform, Res1, Scale);
  2892. tnsGlobalMatrixChanged(o,1);
  2893. }
  2894. void tnsSetCurrentRoot(tnsObject *o){
  2895. if(o->Type!=TNS_OBJECT_ROOT) return;
  2896. memAssignRef(T->World, &T->World->ActiveRoot, o);
  2897. }
  2898. void tnsInitObjectBase(tnsObject *o, tnsObject *under, char *Name, int Type,
  2899. real AtX, real AtY, real AtZ,
  2900. real RotX, real RotY, real RotZ, real RotW, u8bit RotationMode,
  2901. real Scale){
  2902. if (!o) return;
  2903. strSafeSet(&o->Name, Name);
  2904. o->Type = Type;
  2905. tnsVectorSet3(o->Location,AtX,AtY,AtZ);
  2906. tnsVectorSet4(o->Rotation,RotX,RotY,RotZ,RotW); o->RotationMode = RotationMode;
  2907. tnsVectorSet3(o->Scale,Scale,Scale,Scale);
  2908. o->Show = 1;
  2909. o->DrawMode = GL_LINE_LOOP;
  2910. tnsLoadIdentity44d(o->DeltaTransform);
  2911. tnsSelfTransformValueChanged(o);
  2912. lstAppendItem(&T->World->AllObjects, o);
  2913. if (under){ lstAppendPointer(&under->ChildObjects, o); int isroot=(under->Type==TNS_OBJECT_ROOT);
  2914. tnsObject* root=isroot?under:under->InRoot; memAssignRef(o, &o->InRoot, root);
  2915. if(!isroot){ o->ParentObject=under; }
  2916. }
  2917. }
  2918. int tnsCheckParentable(tnsObject* child, tnsObject* parent){
  2919. if(child==parent||parent->ParentObject==child)return 0; tnsObject* o=parent; while(o=o->ParentObject){ if(o==parent) return 0; } return 1;
  2920. }
  2921. void tnsParentObject(tnsObject *child, tnsObject *parent, int KeepTransform){
  2922. if (!child || !parent || child->ParentObject==parent || parent->ParentObject==child || parent==child) return;
  2923. if (child->ParentObject) lstRemovePointerLeave(&child->ParentObject->ChildObjects, child);
  2924. else lstRemovePointerLeave(&child->InRoot->ChildObjects, child);
  2925. lstAppendPointer(&parent->ChildObjects, child);
  2926. memAssignRef(child, &child->ParentObject, parent);
  2927. if(KeepTransform) tnsGlobalMatrixChanged(child, 1);
  2928. else tnsSelfMatrixChanged(child, 1);
  2929. }
  2930. void tnsUnparentObject(tnsObject *o, int KeepTransform){
  2931. if (!o || !o->ParentObject) return;
  2932. lstRemovePointerLeave(&o->ParentObject->ChildObjects, o);
  2933. lstAppendPointer(&o->InRoot->ChildObjects, o);
  2934. memAssignRef(o, &o->ParentObject, 0);
  2935. if(KeepTransform) tnsGlobalMatrixChanged(o,1);
  2936. else tnsSelfMatrixChanged(o,1);
  2937. }
  2938. void tnsCopyObjectTransformationsLocal(tnsObject* to, tnsObject* from){
  2939. tnsVectorCopy3d(from->Location, to->Location);
  2940. tnsVectorCopy3d(from->Rotation, to->Rotation); to->RotationMode=from->RotationMode;
  2941. tnsVectorCopy3d(from->Scale, to->Scale);
  2942. tnsSelfTransformValueChanged(to);
  2943. }
  2944. void tnsCopyObjectTransformationsGlobal(tnsObject* to, tnsObject* from){
  2945. tnsVectorCopy3d(from->GLocation, to->GLocation);
  2946. tnsVectorCopy3d(from->GRotation, to->GRotation); to->RotationMode=from->RotationMode;
  2947. tnsVectorCopy3d(from->GScale, to->GScale);
  2948. tnsGlobalTransformValueChanged(to);
  2949. }
  2950. void tnsRotateObjectLocalValues(tnsObject *o, real x, real y, real z){
  2951. o->Rotation[0] += x; o->Rotation[1] += y; o->Rotation[2] += z;
  2952. tnsSelfTransformValueChanged(o);
  2953. }
  2954. void tnsSetObjectPositionLocal(tnsObject*o, real x, real y, real z){
  2955. tnsVectorSet3(o->Location,x,y,z); tnsSelfTransformValueChanged(o);
  2956. }
  2957. void tnsResetObjectTransformations(tnsObject* o, int reset_loc,int reset_rot,int reset_sca){
  2958. if(reset_loc){ tnsVectorSet3(o->Location,0,0,0); }
  2959. if(reset_rot){ tnsVectorSet4(o->Rotation,0,0,0,0); }
  2960. if(reset_sca){ tnsVectorSet3(o->Rotation,1,1,1); }
  2961. tnsSelfTransformValueChanged(o);
  2962. }
  2963. void tnsMoveObjectLocal(tnsObject *o, real x, real y, real z){
  2964. tnsMatrix44d mat, res1, res2, res3;
  2965. tnsMakeTranslationMatrix44d(res2, x, y, z);
  2966. tnsMultiply44d(res1, o->SelfTransform, res2);
  2967. memcpy(o->SelfTransform, res1, sizeof(tnsMatrix44d));
  2968. tnsSelfMatrixChanged(o,1);
  2969. }
  2970. void tnsMoveObjectDelta(tnsObject *o, real x, real y, real z){
  2971. tnsMatrix44d mat, res1, res2, res3;
  2972. tnsMakeTranslationMatrix44d(res2, x, y, z);
  2973. tnsMultiply44d(res1, o->DeltaTransform, res2);
  2974. memcpy(o->DeltaTransform, res1, sizeof(tnsMatrix44d));
  2975. tnsExtractDeltaTransformValue(o);
  2976. tnsSelfMatrixChanged(o,1);
  2977. }
  2978. void tnsMoveObjectGlobal(tnsObject *o, real x, real y, real z){
  2979. tnsMatrix44d mat, res1, res2, res3;
  2980. tnsMakeTranslationMatrix44d(res2, x, y, z);
  2981. tnsMultiply44d(res1, res2, o->GlobalTransform); //if reverse then local
  2982. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  2983. tnsGlobalMatrixChanged(o,1);
  2984. }
  2985. void tnsMoveObjectGlobalForDelta(tnsObject *o, real x, real y, real z){
  2986. tnsMatrix44d mat, res1, res2, res3;
  2987. tnsMakeTranslationMatrix44d(res2, x, y, z);
  2988. tnsMultiply44d(res1, res2, o->GlobalTransform); //if reverse then local
  2989. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  2990. tnsGlobalMatrixChangedForDelta(o,1);
  2991. }
  2992. void tnsRotateObjectGlobal(tnsObject *o, real x, real y, real z, real angle, real cx,real cy,real cz){
  2993. tnsMatrix44d tback,tfwd,rot,rot2,res1,res2;
  2994. real xs, ys, zs;
  2995. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  2996. tnsMakeRotationMatrix44d(rot2,-angle,x,y,z);//why?
  2997. tnsMakeTranslationMatrix44d(tfwd, o->GLocation[0],o->GLocation[1],o->GLocation[2]);
  2998. tnsInverse44d(tback,tfwd);
  2999. tnsMultiply44d(res1,o->GlobalTransform,tback);
  3000. tnsMultiply44d(res2,rot,res1);
  3001. tnsMultiply44d(o->GlobalTransform,res2,tfwd);
  3002. tnsVector3d delta; delta[0]=o->GLocation[0]-cx; delta[1]=o->GLocation[1]-cy; delta[2]=o->GLocation[2]-cz;
  3003. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz; tnsVector3d r;
  3004. tnsApplyRotation43d(r,rot2,delta);
  3005. tnsVectorPlus3d(&o->GlobalTransform[12],c,r);
  3006. //memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3007. tnsGlobalMatrixChanged(o,1);
  3008. }
  3009. void tnsRotateObjectLocal(tnsObject *o, real x, real y, real z, real angle){
  3010. tnsMatrix44d tback,tfwd,rot,res1,res2;
  3011. //tnsVector3d gp,gpt; gp[0]=gcx; gp[1]=gcy; gp[2]=gcz;
  3012. //tnsMakeTranslationMatrix44d(tfwd, gcx, gcy, gcz);
  3013. //tnsInverse44d(tback,tfwd);
  3014. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3015. //tnsMultiply44d(res1,o->SelfTransform,tback);
  3016. //tnsMultiply44d(res2,res1,rot);
  3017. //tnsMultiply44d(o->SelfTransform,res2,tfwd);
  3018. tnsMultiply44d(res1,o->SelfTransform,rot);
  3019. tnsCopyMatrix44d(res1,o->SelfTransform);
  3020. tnsSelfMatrixChanged(o,1);
  3021. }
  3022. void tnsRotateObjectDelta(tnsObject *o, real x, real y, real z, real angle){
  3023. tnsMatrix44d tback,tfwd,rot,res1,res2;
  3024. //tnsVector3d gp,gpt; gp[0]=gcx; gp[1]=gcy; gp[2]=gcz;
  3025. //tnsApplyTransform43d(gpt,o->DeltaTransform,gp);
  3026. //tnsMakeTranslationMatrix44d(tfwd, gpt[0]-gcx, gpt[0]-gcy, gpt[0]-gcz);
  3027. //tnsInverse44d(tback,tfwd);
  3028. //tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3029. //tnsMultiply44d(res1,o->SelfTransform,tback);
  3030. //tnsMultiply44d(res2,res1,rot);
  3031. //tnsMultiply44d(o->SelfTransform,res2,tfwd);
  3032. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3033. tnsMultiply44d(res1,o->DeltaTransform,rot);
  3034. tnsCopyMatrix44d(res1,o->DeltaTransform);
  3035. tnsExtractDeltaTransformValue(o);
  3036. tnsSelfMatrixChanged(o,1);
  3037. }
  3038. void tnsRotateObjectGlobalForDelta(tnsObject *o, real x, real y, real z, real angle, real cx,real cy,real cz){
  3039. tnsMatrix44d tback,tfwd,rot,rot2,res1,res2;
  3040. real xs, ys, zs;
  3041. tnsMakeRotationMatrix44d(rot,angle,x,y,z);
  3042. tnsMakeRotationMatrix44d(rot2,-angle,x,y,z);//why?
  3043. tnsMakeTranslationMatrix44d(tfwd, o->GLocation[0],o->GLocation[1],o->GLocation[2]);
  3044. tnsInverse44d(tback,tfwd);
  3045. tnsMultiply44d(res1,o->GlobalTransform,tback);
  3046. tnsMultiply44d(res2,rot,res1);
  3047. tnsMultiply44d(o->GlobalTransform,res2,tfwd);
  3048. tnsVector3d delta; delta[0]=o->GLocation[0]-cx; delta[1]=o->GLocation[1]-cy; delta[2]=o->GLocation[2]-cz;
  3049. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz; tnsVector3d r;
  3050. tnsApplyRotation43d(r,rot2,delta);
  3051. tnsVectorPlus3d(&o->GlobalTransform[12],c,r);
  3052. //memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3053. tnsGlobalMatrixChangedForDelta(o,1);
  3054. }
  3055. void tnsScaleObject(tnsObject *o, real x,real y,real z, real cx,real cy,real cz){
  3056. tnsMatrix44d sca,res1,res2;
  3057. tnsMakeScaleMatrix44d(sca,x,y,z);
  3058. tnsMultiply44d(res1,o->GlobalTransform,sca);
  3059. tnsVector3d delta; delta[0]=res1[12]-cx; delta[1]=res1[13]-cy; delta[2]=res1[14]-cz;
  3060. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz;
  3061. delta[0]*=x; delta[1]*=y; delta[2]*=z;
  3062. tnsVectorPlus3d(&res1[12],c,delta);
  3063. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3064. tnsGlobalMatrixChanged(o,1);
  3065. }
  3066. void tnsScaleObjectDelta(tnsObject *o, real x,real y,real z, real cx,real cy,real cz){
  3067. tnsMatrix44d sca,res1,res2;
  3068. tnsMakeScaleMatrix44d(sca,x,y,z);
  3069. tnsMultiply44d(res1,o->GlobalTransform,sca);
  3070. tnsVector3d delta; delta[0]=res1[12]-cx; delta[1]=res1[13]-cy; delta[2]=res1[14]-cz;
  3071. tnsVector3d c; c[0]=cx; c[1]=cy; c[2]=cz;
  3072. delta[0]*=x; delta[1]*=y; delta[2]*=z;
  3073. tnsVectorPlus3d(&res1[12],c,delta);
  3074. memcpy(o->GlobalTransform, res1, sizeof(tnsMatrix44d));
  3075. tnsGlobalMatrixChangedForDelta(o,1);
  3076. }
  3077. void tnsZoomViewingCamera(tnsCamera *c, real Ratio){
  3078. if (c->FocusDistance < 0.1 && Ratio > 0) return;
  3079. tnsMoveObjectLocal(c, 0, 0, -c->FocusDistance * Ratio);
  3080. c->FocusDistance *= (1 - Ratio);
  3081. }
  3082. void tnsRotateViewingCamera(tnsCamera *c, real x, real z){
  3083. tnsMoveObjectLocal(c, 0, 0, -c->FocusDistance);
  3084. tnsRotateObjectLocalValues(c, x, 0, z);
  3085. tnsMoveObjectLocal(c, 0, 0, c->FocusDistance);
  3086. }
  3087. void tnsGetCameraMovingDeltas(tnsCamera *c, int ViewportW, int ViewportH, real x, real y, tnsVector4d p){
  3088. memset(p, 0, sizeof(tnsVector4d));
  3089. tnsVector4d tp = {0};
  3090. tnsMatrix44d combine, projection, projinv, vpinv, vp;
  3091. tnsLoadIdentity44d(projection);
  3092. tnsMakePerspectiveMatrix44d(projection, c->FOV, (real)ViewportW / (real)ViewportH, c->ZMin, c->ZMax);
  3093. tnsMakeViewportMatrix44d(vp, ViewportW, ViewportH, c->ZMax, c->ZMin);
  3094. tnsInverse44d(projinv, projection);
  3095. tnsInverse44d(vpinv, vp);
  3096. p[2] = -c->FocusDistance;
  3097. p[3] = 1;
  3098. tnsApplyTransform44d(tp, projection, p);
  3099. tnsVectorMultiSelf3d(tp, 1 / tp[3]);
  3100. tnsApplyTransform43d(p, vp, tp);
  3101. p[0] += x;
  3102. p[1] += y;
  3103. tnsApplyTransform43d(tp, vpinv, p);
  3104. tnsVectorMultiSelf3d(tp, tp[3]);
  3105. tnsApplyTransform44d(p, projinv, tp);
  3106. }
  3107. void tnsTranslateViewingCamera(tnsCamera *c, int ViewportW, int ViewportH, real x, real y){
  3108. tnsVector4d p={0};
  3109. tnsGetCameraMovingDeltas(c,ViewportW, ViewportH, x,y,p);
  3110. tnsMoveObjectLocal(c, p[0], p[1], 0);
  3111. }
  3112. tnsObject *tnsCreateRootObject(char *name, int Use2D){
  3113. tnsWorld *w = T->World;
  3114. tnsRootObject *o = memAcquireHyper(sizeof(tnsRootObject));
  3115. o->Base.Type==TNS_OBJECT_ROOT;
  3116. strSafeSet(&o->Base.Name, name);
  3117. lstAppendItem(&w->RootObjects, o);
  3118. memAssignRef(w,&w->ActiveRoot,o);
  3119. o->Base.Drivers=memAcquire(sizeof(laRackPageCollection));
  3120. o->Is2D=Use2D;
  3121. return o;
  3122. }
  3123. void tnsDestroyRootObject(tnsObject *root){
  3124. tnsWorld *w = T->World;
  3125. memAssignRef(w,&w->ActiveRoot,root->Item.pPrev ? root->Item.pPrev : root->Item.pNext ? root->Item.pNext : 0);
  3126. root->Evaluated.Done=root->EvaluatedPlay.Done=0;
  3127. tnsFreeEvaluatedArray(&root->Evaluated);
  3128. tnsClearPlayDuplicate(root);
  3129. if(root->EvaluatedPlay.Commands) tnsFreeEvaluatedArray(&root->EvaluatedPlay);
  3130. tnsFreeEvaluatedScene(&root->EvaluatedPlay);
  3131. //destroy rack page; and then release memory;
  3132. laRackPage*rp;
  3133. while(rp=lstPopItem(&root->Drivers->Pages)){
  3134. laNodeRack* rr; while(rr=lstPopItem(&rp->Racks)){ laDestroyRack(rr); }
  3135. memLeave(rp);
  3136. }
  3137. memLeave(root->Drivers); // root->Drivers=0; never reset address for single, see la_GiveDiffCommand()
  3138. lstRemoveItem(&w->RootObjects, root);
  3139. tnsObject*co;
  3140. while(co=lstPopPointerLeave(&root->ChildObjects)){ tnsDestroyObject(co); }
  3141. strSafeDestroy(&root->Name);
  3142. memLeave(root);
  3143. }
  3144. void tnsDestroyObject(tnsObject *o){
  3145. if(o->Type==TNS_OBJECT_ROOT){ tnsDestroyRootObject(o); return; }
  3146. tnsFreeEvaluatedArray(&o->Evaluated);
  3147. tnsClearPlayDuplicate(o);
  3148. if(o->EvaluatedPlay.Commands) tnsFreeEvaluatedArray(&o->EvaluatedPlay);
  3149. tnsFreeEvaluatedScene(&o->EvaluatedPlay);
  3150. tnsUnparentObject(o,1);
  3151. while(o->ChildObjects.pFirst){ tnsUnparentObject(((laListItemPointer*)o->ChildObjects.pFirst)->p, 1); }
  3152. lstRemoveItem(&T->World->AllObjects, o);
  3153. if(o->InRoot){ lstRemovePointerLeave(&o->InRoot->ChildObjects, o);
  3154. tnsInvalidateEvaluation(o);
  3155. if(o->InRoot->Active==o){ memAssignRef(o->InRoot,&o->InRoot->Active,0); }
  3156. }
  3157. if(o->Type==TNS_OBJECT_MESH){ tnsMeshObject* mo=o;
  3158. if(mo->v) arrFree(&mo->v, &mo->maxv); if(mo->e) arrFree(&mo->e, &mo->maxe);
  3159. if(mo->f){ for(int i=0;i<mo->totf;i++){ free(mo->f[i].loop); mo->f[i].loop=0; } arrFree(&mo->f, &mo->maxf); }
  3160. mo->totv=mo->tote=mo->totf=0;
  3161. tnsInvalidateMeshBatch(o);
  3162. tnsMaterialSlot* ms;
  3163. while(ms=lstPopItem(&mo->Materials)){ memLeave(ms); } memAssignRef(mo,&mo->CurrentMaterial,0);
  3164. }
  3165. strSafeDestroy(&o->Name);
  3166. memLeave(o);
  3167. }
  3168. tnsCamera *tnsCreateCamera(tnsObject *under, char *Name, real FOV,
  3169. real AtX, real AtY, real AtZ,
  3170. real RotX, real RotY, real RotZ,
  3171. real FocusDistance){
  3172. tnsCamera *c; tnsWorld *w = T->World;
  3173. c = memAcquireHyper(sizeof(tnsCamera));
  3174. tnsInitObjectBase(&c->Base, under, Name, TNS_OBJECT_CAMERA, AtX, AtY, AtZ, RotX, RotY, RotZ, 1.0f, TNS_ROTATION_XYZ_EULER, 1.0f);
  3175. c->FOV = FOV;
  3176. c->CameraType = TNS_CAMERA_PERSP;
  3177. c->ZMin = 0.1f;
  3178. c->ZMax = 200.0f;
  3179. c->FocusDistance = FocusDistance;
  3180. c->OrthScale = 1.0f;
  3181. return c;
  3182. }
  3183. tnsObject *tnsCreateInstancer(tnsObject *under, char *Name, real AtX, real AtY, real AtZ){
  3184. tnsObject *o; tnsWorld *w = T->World; if (!under) return 0;
  3185. o = memAcquireHyper(sizeof(tnsInstancer));
  3186. tnsInitObjectBase(o, under, Name, TNS_OBJECT_INSTANCER, AtX, AtY, AtZ, 0, 0, 0, 1.0f, TNS_ROTATION_XYZ_EULER, 1.0f);
  3187. return o;
  3188. }
  3189. tnsLight *tnsCreateLight(tnsObject *under, char *Name, real AtX, real AtY, real AtZ, real Strength, int UniDirectional){
  3190. tnsLight *l; tnsWorld *w = T->World; if (!under) return 0;
  3191. tnsObject* root=under->Type==TNS_OBJECT_ROOT?under:under->InRoot;
  3192. if (UniDirectional&&under){
  3193. if(root){ if(root->ParentObject) return root->ParentObject; }
  3194. }
  3195. l = memAcquireHyper(sizeof(tnsLight));
  3196. tnsInitObjectBase(&l->Base, under, Name, TNS_OBJECT_LIGHT, AtX, AtY, AtZ, 0, 0, 0, 1.0f, TNS_ROTATION_XYZ_EULER, 1.0f);
  3197. l->Strength = Strength;
  3198. l->UniDirectional = UniDirectional;
  3199. // ?????????? WTF
  3200. //if (root && UniDirectional && !root->ParentObject) memAssignRef(root, &root->ParentObject,l);
  3201. return l;
  3202. }
  3203. int tnsSizeOfObject(tnsObject* o){
  3204. switch(o->Type){
  3205. case TNS_OBJECT_ROOT: return sizeof(tnsRootObject);
  3206. case TNS_OBJECT_INSTANCER: return sizeof(tnsInstancer);
  3207. case TNS_OBJECT_MESH: return sizeof(tnsMeshObject);
  3208. case TNS_OBJECT_CAMERA: return sizeof(tnsCamera);
  3209. case TNS_OBJECT_LIGHT: return sizeof(tnsLight);
  3210. default: return sizeof(tnsObject);
  3211. }
  3212. }
  3213. tnsObject* tnsDuplicateObject(tnsObject* o){
  3214. tnsMeshObject* to = memAcquireHyper(tnsSizeOfObject(o));
  3215. tnsInitObjectBase(to, o->ParentObject?o->ParentObject:o->InRoot, o->Name->Ptr, TNS_OBJECT_MESH,0,0,0,0,0,0,0,0,1);
  3216. tnsCopyObjectTransformationsLocal(to,o);
  3217. }
  3218. int tnsAnyObjectsSelected(tnsObject *root){
  3219. for(laListItemPointer* lip=root->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsObject* o=lip->p; if(o->Flags&TNS_OBJECT_FLAGS_SELECTED) return 1;
  3220. if(o->ChildObjects.pFirst && tnsAnyObjectsSelected(o)) return 1;
  3221. } return 0;
  3222. }
  3223. void tnsDeselectAllObjects(tnsObject *root){
  3224. for(laListItemPointer* lip=root->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsObject* o=lip->p; o->Flags&=(~TNS_OBJECT_FLAGS_SELECTED);
  3225. if(o->ChildObjects.pFirst)tnsDeselectAllObjects(o);
  3226. }
  3227. memAssignRef(root,&root->Active,0);
  3228. tnsInvalidateEvaluation(root);
  3229. }
  3230. void tnsSelectAllObjects(tnsObject *root){
  3231. for(laListItemPointer* lip=root->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsObject* o=lip->p; o->Flags|=TNS_OBJECT_FLAGS_SELECTED;
  3232. if(o->ChildObjects.pFirst)tnsSelectAllObjects(o);
  3233. }
  3234. tnsInvalidateEvaluation(root);
  3235. }
  3236. void tnsSelectObject(tnsObject* o, int Select, int Toggle){
  3237. if(!o) return;
  3238. if(Toggle) tnsSelectObject(o,(o->Flags&TNS_OBJECT_FLAGS_SELECTED?0:1),0);
  3239. elif(Select) o->Flags|=TNS_OBJECT_FLAGS_SELECTED; else o->Flags&=(~TNS_OBJECT_FLAGS_SELECTED);
  3240. tnsInvalidateEvaluation(o);
  3241. }
  3242. void tnsGetCameraProjection(tnsMatrix44d* mat, int w, int h, tnsCamera* Camera){
  3243. tnsMatrix44d inv, result;
  3244. tnsMakePerspectiveMatrix44d(mat, Camera->FOV, (real)w / (real)h, Camera->ZMin, Camera->ZMax);
  3245. }
  3246. void tnsGetCameraViewProjection(tnsMatrix44d* mat, int w, int h, tnsCamera* Camera){
  3247. tnsMatrix44d inv, result;
  3248. tnsMakePerspectiveMatrix44d(mat, Camera->FOV, (real)w / (real)h, Camera->ZMin, Camera->ZMax);
  3249. tnsInverse44d(inv, Camera->Base.GlobalTransform);
  3250. tnsMultiply44d(result, mat, inv);
  3251. memcpy(mat, result, sizeof(tnsMatrix44d));
  3252. }
  3253. void tnsApplyCameraView(int W, int H, tnsCamera *Camera){
  3254. tnsMatrixStackItem *tmsi = tKnlGetCurrentMatStackItem();
  3255. tnsShader *current_shader = 0;
  3256. real *mat;
  3257. tnsMatrix44d result, inv;
  3258. if (!Camera) return;
  3259. mat = tnsGetProjectionMatrix();
  3260. tnsMakePerspectiveMatrix44d(mat, Camera->FOV, (real)W / (real)H, Camera->ZMin, Camera->ZMax);
  3261. if (current_shader = T->CurrentShader){
  3262. tnsShaderApplyProjection(current_shader, mat);
  3263. tnsShaderApplyProjectionInverse(current_shader, mat);
  3264. }
  3265. tnsResetViewMatrix();
  3266. mat = tnsGetViewMatrix();
  3267. tnsInverse44d(inv, Camera->Base.GlobalTransform);
  3268. tnsMultiply44d(result, mat, inv);
  3269. memcpy(mat, result, sizeof(tnsMatrix44d));
  3270. if (current_shader = T->CurrentShader){
  3271. tnsShaderApplyView(current_shader, result);
  3272. if(current_shader->uViewPos>-1) glUniform3f(current_shader->uViewPos,LA_COLOR3(Camera->Base.GLocation));
  3273. tnsVectorSet3v(T->SetViewPos,Camera->Base.GLocation);
  3274. }
  3275. }
  3276. void tnsApplyShadowCameraView(tnsLight *Light){
  3277. tnsMatrixStackItem *tmsi = tKnlGetCurrentMatStackItem();
  3278. tnsShader *current_shader = 0;
  3279. tnsMatrix44d mat;
  3280. tnsMatrix44d result, inv;
  3281. if (!Light || !Light->UniDirectional) return;
  3282. //mat = tnsGetProjectionMatrix();
  3283. tnsMakeOrthoMatrix44d(mat, -1000,1000,-1000,1000,-1000,1000);
  3284. tnsInverse44d(inv, Light->Base.GlobalTransform);
  3285. tnsMultiply44d(result, mat, inv);
  3286. memcpy(mat, result, sizeof(tnsMatrix44d));
  3287. if (current_shader = T->CurrentShader){
  3288. tnsShaderApplyShadowMatrix(current_shader,mat);
  3289. }
  3290. }
  3291. void tnsApplyModelMatrix(tnsMatrix44d m){
  3292. tnsShader *current_shader = 0; real *mat;
  3293. if (!m) return;
  3294. mat = tnsGetModelMatrix();
  3295. memcpy(mat, m, sizeof(tnsMatrix44d));
  3296. if (current_shader = T->CurrentShader){ tnsShaderApplyModel(current_shader, mat); }
  3297. }
  3298. void tnsLookAt(tnsObject *o, tnsVector3d Target, tnsVector3d Up){
  3299. tnsVector4d target = {0};
  3300. tnsMatrix44d mat, res, res2;
  3301. real *d;
  3302. tnsShader *current_shader = 0;
  3303. d = tnsGetModelMatrix();
  3304. tnsMakeZTrackingMatrix44d(mat, o->GLocation, target, Up);
  3305. tnsLoadIdentity44d(res);
  3306. tnsMakeTranslationMatrix44d(res,o->GLocation[0],o->GLocation[1],o->GLocation[2]);
  3307. tnsMultiply44d(res2, res, mat);
  3308. memcpy(o->SelfTransform, res2, sizeof(tnsMatrix44d));
  3309. tnsSelfMatrixChanged(o,1);
  3310. if (current_shader = T->CurrentShader){
  3311. tnsShaderApplyModel(current_shader, d);
  3312. }
  3313. }
  3314. void tnsDrawCamera(tnsObject *o){
  3315. tnsCamera *c = o;
  3316. real fov_2 = c->FOV / 2;
  3317. real ex, ey, ez; ey = 10 * sin(fov_2); ex = ey; ez = 10 * cos(fov_2);
  3318. tnsColor4d(1, 1, 1, 1);
  3319. tnsVertex3d(ex, ey, -ez); tnsVertex3d(ex, -ey, -ez); tnsVertex3d(0.0, 0.0, 0.0);
  3320. tnsVertex3d(ex, ey, -ez); tnsVertex3d(-ex, ey, -ez); tnsVertex3d(0.0, 0.0, 0.0);
  3321. tnsVertex3d(-ex, -ey, -ez); tnsVertex3d(-ex, ey, -ez);
  3322. tnsPackAs(GL_LINE_STRIP);
  3323. tnsFlush();
  3324. }
  3325. void tnsDrawCross(real x,real y,real z,real x1,real x2,real y1,real y2,real z1,real z2){
  3326. tnsVertex3d(x+x1, y+0.0, z+0.0); tnsVertex3d(x+x2, y+0.0, z+0.0);
  3327. tnsVertex3d(x+0.0,y+ y1, z+0.0); tnsVertex3d(x+0.0,y+ y2, z+0.0);
  3328. tnsVertex3d(x+0.0,y+ 0.0,z+ z1); tnsVertex3d(x+0.0,y+ 0.0,z+ z2);
  3329. }
  3330. void tnsDrawPlaceholder(tnsObject* o, tnsEvaluateData* ed){
  3331. if(T->BindedShader==T->SelectionShader){
  3332. int i=o->SelectID; real color[4]={0,0,0,1}; TNS_ID_TO_COLOR(color,i); tnsColor4dv(color);
  3333. }else{
  3334. if(ed->FillOutline && (!(o->Flags&TNS_OBJECT_FLAGS_SELECTED))) return;
  3335. if(!ed->FillOutline && (o->Flags&TNS_OBJECT_FLAGS_SELECTED)) return;
  3336. if(o==ed->Active){ tnsColor4dv(laAccentColor(LA_BT_TEXT_ACTIVE)); }
  3337. elif(o->Flags&TNS_OBJECT_FLAGS_SELECTED){ tnsColor4dv(laAccentColor(LA_BT_NORMAL)); }
  3338. else tnsColor4dv(laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER));
  3339. }
  3340. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1);
  3341. tnsPackAs(GL_LINES);
  3342. tnsFlush();
  3343. }
  3344. void tnsDrawEmptySelectionID(tnsEvaluatedInstance* ei, void* unused){
  3345. int i=ei->InstanceSelectionID; real color[4]={0,0,0,1}; TNS_ID_TO_COLOR(color,i); tnsColor4dv(color);
  3346. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1); tnsPackAs(GL_LINES); tnsFlush();
  3347. }
  3348. void tnsDrawEmptyOutline(tnsEvaluatedInstance* ei, void* unused){
  3349. real* color=(ei->IsActive)?laAccentColor(LA_BT_TEXT):laAccentColor(LA_BT_NORMAL); tnsColor4dv(color);
  3350. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1); tnsLineWidth(3);tnsPackAs(GL_LINES); tnsLineWidth(1); tnsFlush();
  3351. }
  3352. void tnsDrawEmptyObject(tnsEvaluatedInstance* ei, void* unused){
  3353. tnsColor4dv(laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER));
  3354. tnsDrawCross(0,0,0,-0.2,1,-0.2,1,-0.2,1);tnsLineWidth(3); tnsPackAs(GL_LINES); tnsLineWidth(1); tnsFlush();
  3355. }
  3356. void tnsEvaluateEmptyObject(tnsObject* o, tnsEvaluateData* ed){
  3357. tnsAddEvaluatedInstance(ed,o,tnsDrawEmptyObject,TNS_EVAL_LAYER_SOLID,0,0,0);
  3358. if(ed->FillOutline && o->Flags&TNS_OBJECT_FLAGS_SELECTED){
  3359. tnsAddEvaluatedInstance(ed,o,tnsDrawEmptyOutline,TNS_EVAL_LAYER_OUTLINE,ed->Active==o,0,0);
  3360. }
  3361. if(ed->FillSelectionID){
  3362. tnsAddEvaluatedInstance(ed,o,tnsDrawEmptySelectionID,TNS_EVAL_LAYER_SELECTION,0,1,o->SelectID);
  3363. }
  3364. }
  3365. void tnsPushEvaluateMatrixWith(tnsEvaluateData* ed, tnsMatrix44d mat){
  3366. arrEnsureLength(&ed->MatArr,ed->NextMat,&ed->MaxMat,sizeof(tnsMatrix44d)); if(ed->NextMat<1) return;
  3367. real* new=ed->MatArr[ed->NextMat];
  3368. tnsMultiply44d(new, ed->MatArr[ed->NextMat-1], mat);
  3369. ed->NextMat++;
  3370. }
  3371. void tnsPopEvaluateMatrix(tnsEvaluateData* ed){ ed->NextMat--; }
  3372. void tnsEvaluateInstancerObject(tnsInstancer* o, tnsEvaluateData* ed){
  3373. int origid=ed->OverrideID; ed->OverrideID = o->Base.SelectID;
  3374. tnsEvaluateEmptyObject(o,ed);
  3375. int origoutline=ed->FillOutline; ed->FillOutline=0;
  3376. if(o->Instance){
  3377. tnsObject* inst=o->Instance;
  3378. if(ed->SceneEvaluateMode){ inst=tnsEnsurePlayDuplicate(inst); }
  3379. for(laListItemPointer* lip=ed->ParentStack.pFirst;lip;lip=lip->pNext){
  3380. if(lip->p == inst || lip->p==o->Instance){ goto eval_inst_cleanup; }
  3381. }
  3382. tnsPushEvaluateMatrixWith(ed,o->Base.GlobalTransform);
  3383. tnsEvaluateObjectTree(inst, ed, ed->SceneEvaluateMode);
  3384. tnsPopEvaluateMatrix(ed);
  3385. }
  3386. eval_inst_cleanup:
  3387. ed->OverrideID=origid; ed->FillOutline=origoutline;
  3388. }
  3389. void tnsLuaEnsureNode(lua_State* L,int index,tnsObject* o);
  3390. void tnsLuaRunNode(lua_State* L, tnsEvaluatedNode* en, char* func, tnsObject* root);
  3391. void tnsEvaluateThisObject(tnsObject *o, tnsEvaluateData* ed){
  3392. tnsEvaluatedNode* CP,*CC;
  3393. if(ed->SceneEvaluateMode){
  3394. tnsEvaluateSyncNode(ed,o);
  3395. if(o->Type==TNS_OBJECT_INSTANCER){
  3396. CP=ed->Scene->CurrentParent; CC=ed->Scene->CurrentChild;
  3397. ed->Scene->CurrentParent=ed->Scene->CurrentChild; ed->Scene->CurrentChild=ed->Scene->CurrentParent->Children.pFirst;
  3398. }
  3399. if(o->Type==TNS_OBJECT_ROOT){ tnsEvaluatedNode* en=ed->Scene->CurrentChild;
  3400. tnsLuaEnsureNode(ed->L,en->LuaID,o);
  3401. tnsLuaRunNode(ed->L,en,"run",o);
  3402. }
  3403. }
  3404. if (!o->Show) return;
  3405. switch (o->Type){
  3406. case TNS_OBJECT_MESH: tnsEvaluateMeshObject(o, ed); break;
  3407. case TNS_OBJECT_INSTANCER:
  3408. tnsEvaluateInstancerObject(o,ed);
  3409. if(ed->SceneEvaluateMode){ ed->Scene->CurrentParent=CP; ed->Scene->CurrentChild=CC;}
  3410. break;
  3411. case TNS_OBJECT_CAMERA: tnsDrawCamera(o); break;
  3412. default: tnsEvaluateEmptyObject(o,ed); break;
  3413. }
  3414. }
  3415. void tnsClearPlayDuplicate(tnsObject* o){
  3416. if(!o || !o->PlayDuplicate) return;
  3417. while(lstPopPointer(&o->PlayDuplicate->ChildObjects));
  3418. for(laListItemPointer* lip=o->ChildObjects.pFirst;lip;lip=lip->pNext){
  3419. tnsObject*co=lip->p; tnsClearPlayDuplicate(co);
  3420. }
  3421. if(o->Type==TNS_OBJECT_INSTANCER){ tnsInstancer* oi=o; tnsClearPlayDuplicate(oi->Instance); }
  3422. memFree(o->PlayDuplicate); o->PlayDuplicate=0;
  3423. }
  3424. void tnsFreeEvaluatedNode(tnsEvaluatedNode* n){
  3425. tnsEvaluatedNode* en;
  3426. while(en=lstPopItem(&n->Children)){ tnsFreeEvaluatedNode(en); }
  3427. n->Target->LuaCacheID=0;
  3428. memFree(n);
  3429. }
  3430. void tnsFreeEvaluatedScene(tnsEvaluateData* ed){
  3431. if(!ed->Scene) return;
  3432. if(ed->Scene->Root) tnsFreeEvaluatedNode(ed->Scene->Root);
  3433. logPrintNew("Shutting down Lua for the evaluated scene.\n");
  3434. lua_close(ed->L);
  3435. memFree(ed->Scene); ed->Scene=0;
  3436. }
  3437. void tnsClearPlayState(tnsObject* o){
  3438. tnsClearPlayDuplicate(o);
  3439. if(o->EvaluatedPlay.Commands) tnsFreeEvaluatedArray(&o->EvaluatedPlay);
  3440. tnsFreeEvaluatedScene(&o->EvaluatedPlay);
  3441. }
  3442. tnsObject* tnsEnsurePlayDuplicate(tnsObject* o){
  3443. if(o->Flags&TNS_OBJECT_FLAGS_PLAY_DUPLICATE) return o;
  3444. if(o->PlayDuplicate) return o->PlayDuplicate;
  3445. int obsize=tnsSizeOfObject(o);
  3446. tnsObject* dup=memAcquireHyper(obsize);
  3447. memcpy(dup,o,obsize); o->PlayDuplicate=dup;
  3448. dup->ChildObjects.pFirst=dup->ChildObjects.pLast=0;
  3449. for(laListItemPointer* lip=o->ChildObjects.pFirst;lip;lip=lip->pNext){
  3450. tnsObject*co=lip->p; tnsEnsurePlayDuplicate(co);
  3451. lstAppendPointer(&dup->ChildObjects,co->PlayDuplicate);
  3452. co->PlayDuplicate->ParentObject=o->ParentObject?dup:0; //objects directly under root doesn't have parent object
  3453. }
  3454. if(o->Type==TNS_OBJECT_INSTANCER){ tnsInstancer* oi=o; tnsEnsurePlayDuplicate(oi->Instance); }
  3455. dup->Flags|=TNS_OBJECT_FLAGS_PLAY_DUPLICATE;
  3456. return o->PlayDuplicate;
  3457. }
  3458. void tnsFreePlayDuplicate(tnsObject* o){
  3459. for(laListItemPointer* lip=o->ChildObjects.pFirst;lip;lip=lip->pNext){ tnsFreePlayDuplicate(lip); }
  3460. memFree(o->PlayDuplicate);
  3461. o->PlayDuplicate=0;
  3462. }
  3463. void tnsLuaSetObject(lua_State* L, tnsObject*o){
  3464. lua_getglobal(L,"ffi"); lua_getfield(L,-1,"cast"); lua_pushstring(L,"struct tnsObject *"); lua_pushlightuserdata(L,o);
  3465. lua_call(L,2,1); lua_remove(L,-2); lua_setfield(L,-2,"object");
  3466. }
  3467. void tnsLuaInit(lua_State* L){
  3468. if(luaL_loadstring(L, LA_TNS_LIB_COMMON) || lua_pcall(L, 0, 0, 0)){ logPrint(" Error loading tns lua libs\n"); };
  3469. lua_settop(L,0);
  3470. lua_newtable(L); lua_setglobal(L,"scene");
  3471. lua_getglobal(L,"scene"); lua_pushstring(L,"nodes"); lua_newtable(L); lua_settable(L,1);
  3472. lua_pushnil(L); lua_setfield(L,1,"node"); lua_pop(L,1);
  3473. }
  3474. void tnsLuaEnsureNode(lua_State* L,int index,tnsObject* o){ lua_settop(L,0);
  3475. lua_getglobal(L,"scene"); lua_getfield(L,1,"nodes");
  3476. lua_pushinteger(L,index); lua_gettable(L,2); if(lua_isnil(L,3) || (!lua_istable(L,3))){
  3477. lua_pushinteger(L,index); lua_newtable(L); lua_settable(L,2); lua_pop(L,1);
  3478. lua_pushinteger(L,index); lua_gettable(L,2);
  3479. lua_pushlightuserdata(L,0); lua_setfield(L,3,"object");
  3480. }
  3481. lua_settop(L,0);
  3482. }
  3483. void tnsLuaRemoveNode(lua_State* L,int index){ lua_settop(L,0);
  3484. lua_getglobal(L,"scene"); lua_pushstring(L,"nodes"); lua_gettable(L,1);
  3485. lua_pushinteger(L,index); lua_pushnil(L); lua_settable(L,2); lua_pop(L,2);
  3486. }
  3487. void tnsLuaRunNode(lua_State* L, tnsEvaluatedNode* en, char* func, tnsObject* root){ lua_settop(L,0); int index=en->LuaID;
  3488. lua_getglobal(L,"scene"); lua_getfield(L,1,"nodes");
  3489. lua_pushinteger(L,index); lua_gettable(L,-2); lua_setfield(L,1,"node");
  3490. lua_getfield(L,1,"node"); tnsLuaSetObject(L,root);
  3491. lua_getfield(L,-1,"scripts");
  3492. if(lua_isnil(L,-1) || (!lua_istable(L,-1))){
  3493. lua_pop(L,1); lua_newtable(L); lua_setfield(L,-2,"scripts"); lua_getfield(L,-1,"scripts");
  3494. }
  3495. if(!en->LuaLoaded){
  3496. if(root->Drivers){
  3497. if(root->LuaCacheID){
  3498. int scrtable=lua_gettop(L);
  3499. lua_pushinteger(L,root->LuaCacheID); lua_gettable(L,2); lua_getfield(L,-1,"scripts");
  3500. lua_pushnil(L); while(lua_next(L,-2)){
  3501. lua_pushvalue(L,-2); lua_pushvalue(L,-2); lua_settable(L,scrtable);
  3502. lua_pop(L,1);
  3503. }
  3504. lua_pop(L,2);
  3505. }else{
  3506. for(laRackPage*rp=root->Drivers->Pages.pFirst;rp;rp=rp->Item.pNext){
  3507. if(!(rp->UseScript&&rp->Script&&rp->Script->Ptr)){ continue; }
  3508. char* debug_name=rp->Name&&rp->Name->Ptr?rp->Name->Ptr:"unamed_driver_page";
  3509. lua_pushinteger(L,lua_objlen(L,-1)+1);
  3510. if(!luaL_loadbuffer(L,rp->Script->Ptr,strlen(rp->Script->Ptr),debug_name)){ lua_call(L,0,1); lua_settable(L,-3); }
  3511. else{ lua_pop(L,2); /* pop error and index */ }
  3512. }
  3513. root->LuaCacheID=en->LuaID;
  3514. }
  3515. }
  3516. en->LuaLoaded=1;
  3517. }
  3518. //lua_getglobal(L,"ddump"); lua_getglobal(L,"scene"); lua_call(L,1,0);
  3519. lua_pushnil(L); while(lua_next(L,-2)){
  3520. lua_getfield(L,-1,func); if((!lua_isnil(L,-1))&&lua_isfunction(L,-1)){
  3521. lua_pushvalue(L,-2); lua_call(L,1,0);
  3522. }
  3523. lua_pop(L,1);
  3524. }
  3525. lua_pop(L,3);
  3526. }
  3527. void tnsAddEvaluatedInstance(tnsEvaluateData* ed, tnsObject* ob, tnsDrawEvaluatedInstanceF Draw, int Layer,
  3528. int IsActive, int MeshSelectionType, int InstanceSelectionID){
  3529. tnsEvaluatedInstance* ei;
  3530. if(Layer==TNS_EVAL_LAYER_SOLID){
  3531. arrEnsureLength(&ed->Commands,ed->NextCommand,&ed->MaxCommand,sizeof(tnsEvaluatedInstance));
  3532. ei=&ed->Commands[ed->NextCommand]; ed->NextCommand++;
  3533. }elif(Layer==TNS_EVAL_LAYER_OUTLINE){
  3534. arrEnsureLength(&ed->Outlines,ed->NextOutline,&ed->MaxOutline,sizeof(tnsEvaluatedInstance));
  3535. ei=&ed->Outlines[ed->NextOutline]; ed->NextOutline++;
  3536. }elif(Layer==TNS_EVAL_LAYER_OVERLAY){
  3537. arrEnsureLength(&ed->Overlays,ed->NextOverlay,&ed->MaxOverlay,sizeof(tnsEvaluatedInstance));
  3538. ei=&ed->Overlays[ed->NextOverlay]; ed->NextOverlay++;
  3539. }elif(Layer==TNS_EVAL_LAYER_SELECTION){
  3540. arrEnsureLength(&ed->Selections,ed->NextSelection,&ed->MaxSelection,sizeof(tnsEvaluatedInstance));
  3541. ei=&ed->Selections[ed->NextSelection]; ed->NextSelection++;
  3542. }else{ return; }
  3543. ei->IsActive=IsActive; ei->MeshSelectionType=MeshSelectionType;
  3544. ei->InstanceSelectionID=ed->OverrideID?ed->OverrideID:InstanceSelectionID;
  3545. ei->Draw=Draw; ei->Object=ob;
  3546. tnsMultiply44d(ei->Mat,ed->MatArr[ed->NextMat-1],ob->GlobalTransform);
  3547. }
  3548. void tnsFreeEvaluatedArray(tnsEvaluateData* ed){
  3549. ed->Done=0;
  3550. arrFree(&ed->Commands,&ed->MaxCommand);
  3551. arrFree(&ed->Outlines,&ed->MaxOutline);
  3552. arrFree(&ed->Overlays,&ed->MaxOverlay);
  3553. arrFree(&ed->Selections,&ed->MaxSelection);
  3554. }
  3555. void tnsInvalidateEvaluation(tnsObject* o){
  3556. if(o->InRoot) o->InRoot->Evaluated.Done=0; else o->Evaluated.Done=0;
  3557. }
  3558. void tnsInvalidatePlayEvaluation(tnsObject* o){
  3559. if(o->InRoot) o->InRoot->EvaluatedPlay.Done=0; else o->EvaluatedPlay.Done=0;
  3560. }
  3561. void tnsSetObjectTreeEvaluationArgs(tnsObject* from, tnsObject* Active, int FillOutline, int FillSelectionID){
  3562. tnsEvaluateData* ed=&from->Evaluated; int set=0;
  3563. #define SETARG(a)\
  3564. if(ed->a==0 && a!=0){ set=1; } ed->a=a;
  3565. SETARG(Active); SETARG(FillOutline); SETARG(FillSelectionID);
  3566. if(set) ed->Done=0;
  3567. }
  3568. tnsEvaluatedNode* tnsAcquireEvaluateNode(tnsEvaluateData* ed){
  3569. if(!ed->Scene->WastedEvaluateNodes.pFirst){ tnsEvaluatedNode* en=memAcquire(sizeof(tnsEvaluatedNode));
  3570. ed->Scene->NextLuaID++; en->LuaID=ed->Scene->NextLuaID; return en; }
  3571. else{ return lstPopItem(&ed->Scene->WastedEvaluateNodes); }
  3572. }
  3573. void tnsEvaluateNewNode(tnsEvaluateData* ed, tnsObject* ob){
  3574. tnsEvaluatedScene* s=ed->Scene;
  3575. tnsEvaluatedNode* en=tnsAcquireEvaluateNode(ed); en->Target=ob;
  3576. tnsMultiply44d(en->Mat,ed->MatArr[ed->NextMat-1],ob->GlobalTransform);
  3577. if(s->CurrentChild) lstInsertItemBefore(&s->CurrentParent->Children,en,s->CurrentChild);
  3578. else lstAppendItem(&s->CurrentParent->Children,en);
  3579. s->CurrentChild = en;
  3580. }
  3581. int tnsEvaluateTryRelinkExistingNode(tnsEvaluateData* ed, tnsObject* ob){
  3582. tnsEvaluatedScene* s=ed->Scene;
  3583. if(!s->CurrentChild) return 0;
  3584. int done=0; for(tnsEvaluatedNode* en=s->CurrentChild->Item.pNext;en;en=en->Item.pNext){
  3585. if(ob==en->Target){ done=1; lstRemoveItem(&s->CurrentParent->Children,en);
  3586. lstInsertItemBefore(&s->CurrentParent->Children,en,s->CurrentChild); break; }
  3587. }
  3588. return done;
  3589. }
  3590. void tnsEvaluateEndNode(tnsEvaluateData* ed, tnsEvaluatedNode* en){
  3591. tnsEvaluatedNode* sen;
  3592. while(sen=lstPopItem(&en->Children)){ tnsEvaluateEndNode(ed,sen); }
  3593. int luaid=en->LuaID; memset(en,0,sizeof(tnsEvaluatedNode)); //memFree(sen);
  3594. en->LuaID=luaid; if(en->LuaID!=0) tnsLuaRemoveNode(ed->L,en->LuaID);
  3595. lstAppendItem(&ed->Scene->WastedEvaluateNodes,en);
  3596. }
  3597. void tnsEvaluateSyncNode(tnsEvaluateData* ed, tnsObject* ob){
  3598. tnsEvaluatedScene* s=ed->Scene;
  3599. if(ob && ((!s->CurrentChild) || (s->CurrentChild->Target!=ob))){
  3600. if(!tnsEvaluateTryRelinkExistingNode(ed,ob)) tnsEvaluateNewNode(ed,ob);
  3601. }
  3602. if((!ob) && s->CurrentChild){ tnsEvaluatedNode* en=s->CurrentChild->Item.pPrev;
  3603. if(en) while(en->Item.pNext){ tnsEvaluatedNode* den=en->Item.pNext;
  3604. lstRemoveItem(&s->CurrentParent->Children,den); tnsEvaluateEndNode(ed,den); }
  3605. s->CurrentChild=0;
  3606. }
  3607. }
  3608. void tnsEnsureEvaluatedScene(tnsEvaluateData* ed, tnsObject* root){
  3609. if(!ed->Scene){
  3610. ed->Scene=memAcquire(sizeof(tnsEvaluatedScene));
  3611. logPrintNew("Starting Lua for evaluated scene.\n");
  3612. ed->L = lua_open(); la_luaLoadLibs(ed->L);
  3613. la_luaPrintStatus(ed->L); tnsLuaInit(ed->L);
  3614. }
  3615. if(!ed->Scene->Root){
  3616. ed->Scene->Root=tnsAcquireEvaluateNode(ed);
  3617. ed->Scene->NextLuaID++; ed->Scene->Root->LuaID=ed->Scene->NextLuaID;
  3618. }
  3619. ed->Scene->CurrentChild=ed->Scene->Root;
  3620. ed->Scene->CurrentChild->Target=root; tnsLoadIdentity44d(ed->Scene->CurrentChild->Mat);
  3621. }
  3622. void tnsPrintEvaluatedNode(tnsEvaluatedNode* en,int level){
  3623. for(int i=0;i<level;i++){ printf(" "); }
  3624. printf("%s\n",en->Target->Name?en->Target->Name->Ptr:"?");
  3625. for(tnsEvaluatedNode* sen=en->Children.pFirst;sen;sen=sen->Item.pNext){
  3626. tnsPrintEvaluatedNode(sen,level+1);
  3627. }
  3628. if(level==0){printf("\n");}
  3629. }
  3630. void tnsEvaluateObjectTree(tnsObject* from, tnsEvaluateData* UseED, int EvaluatePlay){
  3631. if(!from) return;
  3632. tnsObject* UseRoot=from->InRoot?from->InRoot:from;
  3633. tnsEvaluateData* ed=UseED?UseED:(EvaluatePlay?&UseRoot->EvaluatedPlay:&UseRoot->Evaluated);
  3634. ed->SceneEvaluateMode=EvaluatePlay;
  3635. if(ed->Done) return;
  3636. elif(!UseED){ ed->NextCommand=ed->NextOverlay=ed->NextSelection=ed->NextOutline=ed->NextMat=0;
  3637. if(!ed->Commands) arrInitLength(&ed->Commands,16,&ed->MaxCommand,sizeof(tnsEvaluatedInstance));
  3638. if(!ed->Outlines) arrInitLength(&ed->Outlines,16,&ed->MaxOutline,sizeof(tnsEvaluatedInstance));
  3639. if(!ed->Overlays) arrInitLength(&ed->Overlays,16,&ed->MaxOverlay,sizeof(tnsEvaluatedInstance));
  3640. if(!ed->Selections) arrInitLength(&ed->Selections,16,&ed->MaxSelection,sizeof(tnsEvaluatedInstance));
  3641. if(!ed->MatArr) arrInitLength(&ed->MatArr,8,&ed->MaxMat,sizeof(tnsMatrix44d));
  3642. tnsLoadIdentity44d(ed->MatArr[0]); ed->NextMat=1;
  3643. }
  3644. tnsEvaluatedNode* CP,*CC;
  3645. if(ed->SceneEvaluateMode){
  3646. from=tnsEnsurePlayDuplicate(from);
  3647. if(!UseED){ tnsEnsureEvaluatedScene(ed,from); }
  3648. CP=ed->Scene->CurrentParent; CC=ed->Scene->CurrentChild;
  3649. }
  3650. lstPushPointer(&ed->ParentStack,from);
  3651. tnsEvaluateThisObject(from, ed);
  3652. if(ed->SceneEvaluateMode){ ed->Scene->CurrentParent=ed->Scene->CurrentChild; ed->Scene->CurrentChild=ed->Scene->CurrentParent->Children.pFirst; }
  3653. for (laListItemPointer* lip=from->ChildObjects.pFirst;lip;lip=lip->pNext){
  3654. tnsObject *o=lip->p; if (o){ tnsEvaluateObjectTree(o,ed,EvaluatePlay); }
  3655. if(ed->SceneEvaluateMode){ ed->Scene->CurrentChild=ed->Scene->CurrentChild?ed->Scene->CurrentChild->Item.pNext:0; }
  3656. }
  3657. lstPopPointer(&ed->ParentStack);
  3658. if(ed->SceneEvaluateMode){ ed->Scene->CurrentParent=CP; ed->Scene->CurrentChild=CC; }
  3659. if(!UseED){ ed->Done=1;
  3660. //if(ed->Scene){ tnsPrintEvaluatedNode(ed->Scene->Root,0);}
  3661. }
  3662. }
  3663. void tnsDrawLayer(tnsEvaluateData* ed,int Layer,void* CustomData){
  3664. tnsEvaluatedInstance* ei; int next=0;
  3665. if(Layer==TNS_EVAL_LAYER_SOLID){ ei=ed->Commands; next=ed->NextCommand; }
  3666. elif(Layer==TNS_EVAL_LAYER_OUTLINE){ ei=ed->Outlines; next=ed->NextOutline; }
  3667. elif(Layer==TNS_EVAL_LAYER_OVERLAY){ ei=ed->Overlays; next=ed->NextOverlay; }
  3668. elif(Layer==TNS_EVAL_LAYER_SELECTION){ ei=ed->Selections; next=ed->NextSelection; }
  3669. else{ return; } if(!next){ return; }
  3670. for(int i=0;i<next;i++){
  3671. tnsPushMatrix(); tnsApplyModelMatrix(ei->Mat);
  3672. ei->Draw(ei,CustomData);
  3673. tnsPopMatrix();
  3674. ei++;
  3675. }
  3676. }
  3677. void tnsDrawObjectTree(tnsObject* from, int Layers,void* CustomData, int DrawRuntime){
  3678. if(!from) return;
  3679. tnsEvaluateData* ed=DrawRuntime?&from->EvaluatedPlay:&from->Evaluated;
  3680. if(!ed->Done) return;
  3681. if(Layers&TNS_EVAL_LAYER_SOLID){ tnsDrawLayer(ed,TNS_EVAL_LAYER_SOLID,CustomData); }
  3682. if(Layers&TNS_EVAL_LAYER_OUTLINE){ tnsDrawLayer(ed,TNS_EVAL_LAYER_OUTLINE,CustomData);}
  3683. if(Layers&TNS_EVAL_LAYER_OVERLAY){ tnsDrawLayer(ed,TNS_EVAL_LAYER_OVERLAY,CustomData);}
  3684. if(Layers&TNS_EVAL_LAYER_SELECTION){ tnsDrawLayer(ed,TNS_EVAL_LAYER_SELECTION,CustomData); }
  3685. }
  3686. void tnsDrawObjectOrigins(tnsObject *from, tnsObject *active, int AllOrigins){
  3687. tnsObject *o; if(!from) return;
  3688. tnsVector4d pos;
  3689. for (laListItemPointer* lip=from->ChildObjects.pFirst;lip;lip=lip->pNext){
  3690. o=lip->p; if((!AllOrigins) && (o!=active) && (!(o->Flags&TNS_OBJECT_FLAGS_SELECTED))) continue;
  3691. if(o->Type==TNS_OBJECT_MESH && ((tnsMeshObject*)o)->Mode==TNS_MESH_EDIT_MODE){ continue; }
  3692. if(T->BindedShader==T->SelectionShader){ int i=o->SelectID; real color[4]={0,0,0,1}; TNS_ID_TO_COLOR(color,i); tnsColor4dv(color); }
  3693. else{
  3694. if(o==active){ tnsColor4dv(laAccentColor(LA_BT_TEXT_ACTIVE)); }
  3695. elif(o->Flags&TNS_OBJECT_FLAGS_SELECTED){ tnsColor4dv(laAccentColor(LA_BT_NORMAL)); }
  3696. else{ real* c=laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER); tnsColor4d(LA_COLOR3(c),0.5); }
  3697. }
  3698. tnsVertex3d(LA_COLOR3(o->GLocation)); tnsPackAs(GL_POINTS);
  3699. }
  3700. }
  3701. void tnsDrawCursor(tnsObject* root){
  3702. if(!root || root->Type!=TNS_OBJECT_ROOT) return;
  3703. tnsMatrix44d vp; tnsVector4d t; tnsVector4d t1={0,0,0,1};
  3704. tnsMultiply44d(vp,tnsGetProjectionMatrix(),tnsGetViewMatrix());
  3705. tnsApplyTransform44d(t,vp,root->GLocation); real w=t[3]*0.05;
  3706. tnsDrawCross(LA_COLOR3(root->GLocation),-w,w,-w,w,-w,w); tnsColor4d(0,0,0,0.5);
  3707. tnsPackAs(GL_LINES); glLineWidth(5);
  3708. tnsFlush(); w*=0.9;
  3709. tnsDrawCross(LA_COLOR3(root->GLocation),-w,w,-w,w,-w,w); tnsColor4dv(laThemeColor(_LA_THEME_3D_VIEW,LA_BT_BORDER));
  3710. tnsPackAs(GL_LINES); glLineWidth(2);
  3711. tnsFlush(); glLineWidth(1);
  3712. }
  3713. //===================================================================[Material]
  3714. tnsMaterial *tnsCreateMaterial(char *Name){
  3715. tnsMaterial *m; if(!Name || !Name[0]) return 0;
  3716. m = memAcquireHyper(sizeof(tnsMaterial));
  3717. strSafeSet(&m->Name, Name); tnsVectorSet4(m->Color,0.8,0.8,0.8,1);
  3718. m->Page=memAcquire(sizeof(laRackPage));
  3719. lstAppendItem(&T->World->Materials, m);
  3720. return m;
  3721. }
  3722. tnsMaterial *tnsFindMaterial(char *name){
  3723. tnsMaterial *m;
  3724. for (m = T->World->Materials.pFirst; m; m = m->Item.pNext){ if(strSame(m->Name->Ptr, name)) return m; }
  3725. return 0;
  3726. }
  3727. void tnsRemoveMaterial(tnsMaterial* mat){
  3728. lstRemoveItem(&T->World->Materials,mat);
  3729. laNodeRack* rr; while(rr=lstPopItem(&mat->Page->Racks)){ laDestroyRack(rr); }
  3730. strSafeDestroy(&mat->Page->Name); memLeave(mat->Page);
  3731. for(tnsObject* o=T->World->AllObjects.pFirst;o;o=o->Item.pNext){
  3732. if(o->Type!=TNS_OBJECT_MESH) continue; tnsMeshObject* mo=o;
  3733. for(tnsMaterialSlot* msi=mo->Materials.pFirst;msi;msi=msi->Item.pNext){
  3734. if(msi->Material==mat){ memAssignRef(msi,&msi->Material,0); }
  3735. }
  3736. }
  3737. tnsRefreshMaterialLibraries();
  3738. memLeave(mat);
  3739. }
  3740. tnsMaterialSlot* tnsNewMaterialSlot(tnsMeshObject* mo){
  3741. if(mo->Base.Type!=TNS_OBJECT_MESH) return 0; short nextid=0,found=1;
  3742. while(found){ found=0;
  3743. for(tnsMaterialSlot* msi=mo->Materials.pFirst;msi;msi=msi->Item.pNext){
  3744. if(nextid==msi->Index){ found=1; nextid++; continue; }
  3745. }
  3746. }
  3747. tnsMaterialSlot* ms=memAcquire(sizeof(tnsMaterialSlot)); lstAppendItem(&mo->Materials,ms);
  3748. ms->Index=nextid; memAssignRef(ms,&ms->Parent,mo); memAssignRef(mo,&mo->CurrentMaterial,ms);
  3749. return ms;
  3750. }
  3751. void tnsRemoveMaterialSlot(tnsMeshObject* mo, tnsMaterialSlot* ms){
  3752. if(mo->Base.Type!=TNS_OBJECT_MESH) return;
  3753. memAssignRef(mo,&mo->CurrentMaterial,ms->Item.pNext?ms->Item.pNext:ms->Item.pPrev);
  3754. lstRemoveItem(&mo->Materials,ms); memLeave(ms);
  3755. }
  3756. void tnsAssignMaterialSlot(tnsMeshObject* mo, tnsMaterialSlot* ms){
  3757. if(mo->Mode==TNS_MESH_OBJECT_MODE){
  3758. for(int i=0;i<mo->totf;i++){ mo->f[i].mat=ms->Index; }
  3759. }elif(mo->Mode==TNS_MESH_EDIT_MODE){
  3760. for(tnsMFace* f=mo->mf.pFirst;f;f=f->Item.pNext){ if(f->flags&TNS_MESH_FLAG_SELECTED) f->mat=ms->Index; }
  3761. }
  3762. }
  3763. void tnsRefreshMaterialLibraries(){
  3764. strSafeDestroy(&T->World->MaterialLibraries);
  3765. for(tnsMaterial* mat=T->World->Materials.pFirst;mat;mat=mat->Item.pNext){
  3766. if(!mat->AsLibrary || !mat->Page->UseScript) continue;
  3767. if(mat->Page->Script) strSafeAppend(&T->World->MaterialLibraries,mat->Page->Script->Ptr);
  3768. tnsEnsureMaterialShader(mat,1);
  3769. }
  3770. for(tnsMaterial* mat=T->World->Materials.pFirst;mat;mat=mat->Item.pNext){
  3771. if(mat->AsLibrary || !mat->Page->UseScript) continue;
  3772. tnsEnsureMaterialShader(mat,1); tns_InvalidateMeshWithMaterial(mat);
  3773. }
  3774. laNotifyUsers("tns.world");
  3775. }
  3776. void tnsEnsureMaterialShader(tnsMaterial* mat, int Refresh){
  3777. if(Refresh){
  3778. if(mat->Shader && mat->Shader!=T->immShader){ tnsDeleteShaderProgram(mat->Shader); mat->Shader=0; }
  3779. }
  3780. if((!(mat->Page->Script&&mat->Page->Script->Ptr))||mat->AsLibrary){ mat->Shader=T->immShader; return; }
  3781. char* str=mat->Page->Script->Ptr;
  3782. char* lib=T->World->MaterialLibraries?T->World->MaterialLibraries->Ptr:0;
  3783. mat->Shader = tnsNewShaderProgram(
  3784. tnsNewVertexShader(LA_IMM_VERTEX_SHADER),tnsNewFragmentShaderMaterial(LA_OBJECT_FRAGMENT_SHADER,lib,str),-1);
  3785. if(!mat->Shader){ mat->Shader=T->immShader; }
  3786. }
  3787. void tnsPrintMaterials(){
  3788. for(tnsMaterial* m=T->World->Materials.pFirst;m;m=m->Item.pNext){
  3789. printf("%s %d %d\n",(m->Name&&m->Name->Ptr?m->Name->Ptr:""),m,m->Page->Racks.pFirst);
  3790. }
  3791. }
  3792. //==================================================================[Util]
  3793. #define MAX3(a, b, c) \
  3794. a > b ? (a > c ? a : c) : (b > c ? b : c)
  3795. #define MIN3(a, b, c) \
  3796. a < b ? (a < c ? a : c) : (b < c ? b : c)
  3797. extern LA MAIN;
  3798. void tnssRGB2XYZ(tnsVector3d rgb,tnsVector3d xyz){
  3799. tnsMatrix44d mat={0.4124564,0.3575761,0.1804375,0,
  3800. 0.2126729,0.7151522,0.0721750,0,
  3801. 0.0193339,0.1191920,0.9503041,0,0,0,0,0};
  3802. tnsApplyRotation33d(xyz,mat,rgb);
  3803. }
  3804. void tnsClay2XYZ(tnsVector3d rgb,tnsVector3d xyz){
  3805. tnsMatrix44d mat={0.5767309,0.1855540,0.1881852,0,
  3806. 0.2973769,0.6273491,0.0752741,0,
  3807. 0.0270343,0.0706872,0.9911085,0,0,0,0,0};
  3808. tnsApplyRotation33d(xyz,mat,rgb);
  3809. }
  3810. void tnsXYZ2sRGB(tnsVector3d xyz,tnsVector3d rgb){
  3811. tnsMatrix44d mat={3.2404542,-1.5371385,-0.4985314,0,
  3812. -0.9692660,1.8760108,0.0415560,0,
  3813. 0.0556434,-0.2040259,1.0572252,0,0,0,0,0};
  3814. tnsApplyRotation33d(rgb,mat,xyz);
  3815. }
  3816. void tnsXYZ2Clay(tnsVector3d xyz,tnsVector3d rgb){
  3817. tnsMatrix44d mat={2.0413690,-0.5649464,-0.3446944,0,
  3818. -0.9692660,1.8760108,0.0415560,0,
  3819. 0.0134474,-0.1183897,1.0154096,0,0,0,0,0};
  3820. tnsApplyRotation33d(rgb,mat,xyz);
  3821. }
  3822. void tnsRGB2Clay(tnsVector3d rgb, tnsVector3d clay){
  3823. tnsVector3d xyz; tnssRGB2XYZ(rgb,xyz);
  3824. tnsXYZ2Clay(xyz,clay);
  3825. }
  3826. void tnsClay2RGB(tnsVector3d clay, tnsVector3d rgb){
  3827. tnsVector3d xyz; tnsClay2XYZ(clay,xyz);
  3828. tnsXYZ2sRGB(xyz,rgb);
  3829. }
  3830. static real _srgb_transfer_function(real a){
  3831. return .0031308f >= a ? 12.92f * a : 1.055f * powf(a, .4166666666666667f) - .055f;
  3832. }
  3833. static real _srgb_transfer_function_inv(real a){
  3834. return .04045f < a ? powf((a + .055f) / 1.055f, 2.4f) : a / 12.92f;
  3835. }
  3836. void tns2LogsRGBSingle(real* a){
  3837. *a=_srgb_transfer_function(*a);
  3838. }
  3839. void tns2LinearsRGBSingle(real* a){
  3840. *a=_srgb_transfer_function_inv(*a);
  3841. }
  3842. void tns2LogsRGB(real* srgb){
  3843. srgb[0]=_srgb_transfer_function(srgb[0]);
  3844. srgb[1]=_srgb_transfer_function(srgb[1]);
  3845. srgb[2]=_srgb_transfer_function(srgb[2]);
  3846. }
  3847. void tns2LinearsRGB(real* srgb){
  3848. srgb[0]=_srgb_transfer_function_inv(srgb[0]);
  3849. srgb[1]=_srgb_transfer_function_inv(srgb[1]);
  3850. srgb[2]=_srgb_transfer_function_inv(srgb[2]);
  3851. }
  3852. void tnsRGB2OKLAB(real* rgb, real* oklab){
  3853. real l = 0.4122214708f * rgb[0] + 0.5363325363f * rgb[1] + 0.0514459929f * rgb[2];
  3854. real m = 0.2119034982f * rgb[0] + 0.6806995451f * rgb[1] + 0.1073969566f * rgb[2];
  3855. real s = 0.0883024619f * rgb[0] + 0.2817188376f * rgb[1] + 0.6299787005f * rgb[2];
  3856. real l_ = cbrt(l); real m_ = cbrt(m); real s_ = cbrt(s);
  3857. oklab[0]=0.2104542553f*l_ + 0.7936177850f*m_ - 0.0040720468f*s_;
  3858. oklab[1]=1.9779984951f*l_ - 2.4285922050f*m_ + 0.4505937099f*s_;
  3859. oklab[2]=0.0259040371f*l_ + 0.7827717662f*m_ - 0.8086757660f*s_;
  3860. }
  3861. void tnsOKLAB2RGB(real* oklab, real* rgb){
  3862. real l_ = oklab[0] + 0.3963377774f * oklab[1] + 0.2158037573f * oklab[2];
  3863. real m_ = oklab[0] - 0.1055613458f * oklab[1] - 0.0638541728f * oklab[2];
  3864. real s_ = oklab[0] - 0.0894841775f * oklab[1] - 1.2914855480f * oklab[2];
  3865. real l = l_*l_*l_; real m = m_*m_*m_; real s = s_*s_*s_;
  3866. rgb[0]=+4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s;
  3867. rgb[1]=-1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s;
  3868. rgb[2]=-0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s;
  3869. }
  3870. static real _compute_max_saturation(real a, real b){
  3871. real k0, k1, k2, k3, k4, wl, wm, ws;
  3872. if (-1.88170328f * a - 0.80936493f * b > 1){
  3873. k0 = +1.19086277f; k1 = +1.76576728f; k2 = +0.59662641f; k3 = +0.75515197f; k4 = +0.56771245f;
  3874. wl = +4.0767416621f; wm = -3.3077115913f; ws = +0.2309699292f;
  3875. }
  3876. else if (1.81444104f * a - 1.19445276f * b > 1){
  3877. k0 = +0.73956515f; k1 = -0.45954404f; k2 = +0.08285427f; k3 = +0.12541070f; k4 = +0.14503204f;
  3878. wl = -1.2684380046f; wm = +2.6097574011f; ws = -0.3413193965f;
  3879. }
  3880. else{
  3881. k0 = +1.35733652f; k1 = -0.00915799f; k2 = -1.15130210f; k3 = -0.50559606f; k4 = +0.00692167f;
  3882. wl = -0.0041960863f; wm = -0.7034186147f; ws = +1.7076147010f;
  3883. }
  3884. real S = k0 + k1 * a + k2 * b + k3 * a * a + k4 * a * b;
  3885. real k_l = +0.3963377774f * a + 0.2158037573f * b;
  3886. real k_m = -0.1055613458f * a - 0.0638541728f * b;
  3887. real k_s = -0.0894841775f * a - 1.2914855480f * b;
  3888. {
  3889. real l_ = 1.f + S * k_l;
  3890. real m_ = 1.f + S * k_m;
  3891. real s_ = 1.f + S * k_s;
  3892. real l = l_ * l_ * l_;
  3893. real m = m_ * m_ * m_;
  3894. real s = s_ * s_ * s_;
  3895. real l_dS = 3.f * k_l * l_ * l_;
  3896. real m_dS = 3.f * k_m * m_ * m_;
  3897. real s_dS = 3.f * k_s * s_ * s_;
  3898. real l_dS2 = 6.f * k_l * k_l * l_;
  3899. real m_dS2 = 6.f * k_m * k_m * m_;
  3900. real s_dS2 = 6.f * k_s * k_s * s_;
  3901. real f = wl * l + wm * m + ws * s;
  3902. real f1 = wl * l_dS + wm * m_dS + ws * s_dS;
  3903. real f2 = wl * l_dS2 + wm * m_dS2 + ws * s_dS2;
  3904. S = S - f * f1 / (f1 * f1 - 0.5f * f * f2);
  3905. }
  3906. return S;
  3907. }
  3908. static void _find_cusp(real a, real b, real *l, real *c)
  3909. {
  3910. real S_cusp = _compute_max_saturation(a, b);
  3911. real oklab[3]={1, S_cusp * a, S_cusp * b}; real rgb_at_max[3];
  3912. tnsOKLAB2RGB(oklab,rgb_at_max);
  3913. real L_cusp = cbrt(1.f / TNS_MAX3(rgb_at_max[0], rgb_at_max[1], rgb_at_max[2]));
  3914. real C_cusp = L_cusp * S_cusp;
  3915. *l=L_cusp; *c=C_cusp;
  3916. }
  3917. static real _find_gamut_intersection(real a, real b, real L1, real C1, real L0, real cusp_L, real cusp_C)
  3918. {
  3919. real t;
  3920. if (((L1 - L0) * cusp_C - (cusp_L - L0) * C1) <= 0.f) {
  3921. t = cusp_C * L0 / (C1 * cusp_L + cusp_C * (L0 - L1));
  3922. }else{
  3923. t = cusp_C * (L0 - 1.f) / (C1 * (cusp_L - 1.f) + cusp_C * (L0 - L1));
  3924. {
  3925. real dL = L1 - L0; real dC = C1;
  3926. real k_l = +0.3963377774f * a + 0.2158037573f * b;
  3927. real k_m = -0.1055613458f * a - 0.0638541728f * b;
  3928. real k_s = -0.0894841775f * a - 1.2914855480f * b;
  3929. real l_dt = dL + dC * k_l;
  3930. real m_dt = dL + dC * k_m;
  3931. real s_dt = dL + dC * k_s;
  3932. {
  3933. real L = L0 * (1.f - t) + t * L1;
  3934. real C = t * C1;
  3935. real l_ = L + C * k_l;
  3936. real m_ = L + C * k_m;
  3937. real s_ = L + C * k_s;
  3938. real l = l_ * l_ * l_;
  3939. real m = m_ * m_ * m_;
  3940. real s = s_ * s_ * s_;
  3941. real ldt = 3 * l_dt * l_ * l_;
  3942. real mdt = 3 * m_dt * m_ * m_;
  3943. real sdt = 3 * s_dt * s_ * s_;
  3944. real ldt2 = 6 * l_dt * l_dt * l_;
  3945. real mdt2 = 6 * m_dt * m_dt * m_;
  3946. real sdt2 = 6 * s_dt * s_dt * s_;
  3947. real r = 4.0767416621f * l - 3.3077115913f * m + 0.2309699292f * s - 1;
  3948. real r1 = 4.0767416621f * ldt - 3.3077115913f * mdt + 0.2309699292f * sdt;
  3949. real r2 = 4.0767416621f * ldt2 - 3.3077115913f * mdt2 + 0.2309699292f * sdt2;
  3950. real u_r = r1 / (r1 * r1 - 0.5f * r * r2);
  3951. real t_r = -r * u_r;
  3952. real g = -1.2684380046f * l + 2.6097574011f * m - 0.3413193965f * s - 1;
  3953. real g1 = -1.2684380046f * ldt + 2.6097574011f * mdt - 0.3413193965f * sdt;
  3954. real g2 = -1.2684380046f * ldt2 + 2.6097574011f * mdt2 - 0.3413193965f * sdt2;
  3955. real u_g = g1 / (g1 * g1 - 0.5f * g * g2);
  3956. real t_g = -g * u_g;
  3957. real b = -0.0041960863f * l - 0.7034186147f * m + 1.7076147010f * s - 1;
  3958. real b1 = -0.0041960863f * ldt - 0.7034186147f * mdt + 1.7076147010f * sdt;
  3959. real b2 = -0.0041960863f * ldt2 - 0.7034186147f * mdt2 + 1.7076147010f * sdt2;
  3960. real u_b = b1 / (b1 * b1 - 0.5f * b * b2);
  3961. real t_b = -b * u_b;
  3962. t_r = u_r >= 0.f ? t_r : FLT_MAX;
  3963. t_g = u_g >= 0.f ? t_g : FLT_MAX;
  3964. t_b = u_b >= 0.f ? t_b : FLT_MAX;
  3965. t += fmin(t_r, fmin(t_g, t_b));
  3966. }
  3967. }
  3968. }
  3969. return t;
  3970. }
  3971. static real _toe(real x) {
  3972. const real k_1 = 0.206f; const real k_2 = 0.03f; const real k_3 = (1.f + k_1) / (1.f + k_2);
  3973. return 0.5f * (k_3 * x - k_1 + sqrt((k_3 * x - k_1) * (k_3 * x - k_1) + 4 * k_2 * k_3 * x));
  3974. }
  3975. static real _toe_inv(real x) {
  3976. const real k_1 = 0.206f; const real k_2 = 0.03f; const real k_3 = (1.f + k_1) / (1.f + k_2);
  3977. return (x * x + k_1 * x) / (k_3 * (x + k_2));
  3978. }
  3979. static void _to_ST(real cusp_L, real cusp_C, real* _s, real* _t) {
  3980. real L = cusp_L; real C = cusp_C;
  3981. *_s=C / L; *_t=C / (1 - L);
  3982. }
  3983. static void _get_ST_mid(real a_, real b_, real *s,real *t){
  3984. *s = 0.11516993f + 1.f / (
  3985. +7.44778970f + 4.15901240f * b_
  3986. + a_ * (-2.19557347f + 1.75198401f * b_
  3987. + a_ * (-2.13704948f - 10.02301043f * b_
  3988. + a_ * (-4.24894561f + 5.38770819f * b_ + 4.69891013f * a_
  3989. )))
  3990. );
  3991. *t = 0.11239642f + 1.f / (
  3992. +1.61320320f - 0.68124379f * b_
  3993. + a_ * (+0.40370612f + 0.90148123f * b_
  3994. + a_ * (-0.27087943f + 0.61223990f * b_
  3995. + a_ * (+0.00299215f - 0.45399568f * b_ - 0.14661872f * a_
  3996. )))
  3997. );
  3998. }
  3999. static void _get_Cs(real L, real a_, real b_,real *rC_0, real *rC_mid, real *rC_max){
  4000. real cusp_L,cusp_C; _find_cusp(a_, b_,&cusp_L,&cusp_C);
  4001. real C_max = _find_gamut_intersection(a_, b_, L, 1, L,cusp_L,cusp_C);
  4002. real _S,_T; _to_ST(cusp_L,cusp_C,&_S, &_T);
  4003. real k = C_max / fmin((L * _S), (1 - L) * _T);
  4004. real C_mid;{
  4005. real _s, _t; _get_ST_mid(a_, b_,&_s,&_t);
  4006. real C_a = L * _s; real C_b = (1.f - L) * _t;
  4007. C_mid = 0.9f * k * sqrt(sqrt(1.f / (1.f / (C_a * C_a * C_a * C_a) + 1.f / (C_b * C_b * C_b * C_b))));
  4008. }
  4009. real C_0;{
  4010. real C_a = L * 0.4f;
  4011. real C_b = (1.f - L) * 0.8f;
  4012. C_0 = sqrt(1.f / (1.f / (C_a * C_a) + 1.f / (C_b * C_b)));
  4013. }
  4014. *rC_0=C_0; *rC_mid=C_mid; *rC_max=C_max;
  4015. }
  4016. void tnsHCY2RGBLinear(real *hcy, real *rgb){
  4017. real h = hcy[0]; real s = hcy[1]; real l = hcy[2];
  4018. if (l >= 1.0f){ tnsVectorSet3(rgb,1,1,1); return; }
  4019. else if (l <= 0.0f){ tnsVectorSet3(rgb,0,0,0); return; }
  4020. real a_ = cos(2.f * TNS_PI * h);
  4021. real b_ = sin(2.f * TNS_PI * h);
  4022. real L = _toe_inv(l);
  4023. real C_0, C_mid, C_max;
  4024. _get_Cs(L, a_, b_,&C_0,&C_mid,&C_max);
  4025. real mid = 0.8f; real mid_inv = 1.25f;
  4026. real C, t, k_0, k_1, k_2;
  4027. if (s < mid){
  4028. t = mid_inv * s;
  4029. k_1 = mid * C_0;
  4030. k_2 = (1.f - k_1 / C_mid);
  4031. C = t * k_1 / (1.f - k_2 * t);
  4032. }else{
  4033. t = (s - mid)/ (1 - mid);
  4034. k_0 = C_mid;
  4035. k_1 = (1.f - mid) * C_mid * C_mid * mid_inv * mid_inv / C_0;
  4036. k_2 = (1.f - (k_1) / (C_max - C_mid));
  4037. C = k_0 + t * k_1 / (1.f - k_2 * t);
  4038. }
  4039. real okl[3]={L, C * a_, C * b_};
  4040. tnsOKLAB2RGB(okl, rgb);
  4041. }
  4042. void tnsRGB2HCYLinear(real *rgb, real *hcy){
  4043. real lab[3]; real lrgb[3];
  4044. lrgb[0]=rgb[0]; lrgb[1]=rgb[1]; lrgb[2]=rgb[2];
  4045. tnsRGB2OKLAB(lrgb,lab);
  4046. if(lab[0]>=1.0f-1e-4){ tnsVectorSet3(hcy,0,0,1); return; }
  4047. if(lab[0]<=1e-4){ tnsVectorSet3(hcy,0,0,0); return; }
  4048. real C = sqrt(lab[1]*lab[1] + lab[2]*lab[2]);
  4049. real a_ = (!C)?0:(lab[1] / C);
  4050. real b_ = (!C)?0:(lab[2] / C);
  4051. real L = lab[0];
  4052. real h = 0.5f + 0.5f * atan2(-lab[2], -lab[1]) / TNS_PI;
  4053. real C_0, C_mid, C_max;
  4054. _get_Cs(L, a_, b_,&C_0,&C_mid,&C_max);
  4055. real mid = 0.8f; real mid_inv = 1.25f;
  4056. real s;
  4057. if (C < C_mid){
  4058. real k_1 = mid * C_0;
  4059. real k_2 = (1.f - k_1 / C_mid);
  4060. real t = C / (k_1 + k_2 * C);
  4061. s = t * mid;
  4062. }else{
  4063. real k_0 = C_mid;
  4064. real k_1 = (1.f - mid) * C_mid * C_mid * mid_inv * mid_inv / C_0;
  4065. real k_2 = (1.f - (k_1) / (C_max - C_mid));
  4066. real t = (C - k_0) / (k_1 + k_2 * (C - k_0));
  4067. s = mid + (1.f - mid) * t;
  4068. }
  4069. real l = _toe(L);
  4070. hcy[0]=h; hcy[1]=s; hcy[2]=l;
  4071. }
  4072. void tnsHCY2RGB(real *hcy, real *rgb){
  4073. tnsHCY2RGBLinear(hcy,rgb);
  4074. rgb[0]=_srgb_transfer_function(rgb[0]);
  4075. rgb[1]=_srgb_transfer_function(rgb[1]);
  4076. rgb[2]=_srgb_transfer_function(rgb[2]);
  4077. }
  4078. void tnsRGB2HCY(real *rgb, real *hcy){
  4079. real lrgb[3];
  4080. lrgb[0]=_srgb_transfer_function_inv(rgb[0]);
  4081. lrgb[1]=_srgb_transfer_function_inv(rgb[1]);
  4082. lrgb[2]=_srgb_transfer_function_inv(rgb[2]);
  4083. tnsRGB2HCYLinear(lrgb,hcy);
  4084. }
  4085. void tnsClearAll(){
  4086. glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
  4087. }
  4088. void tnsClearColorv(real *rgba){
  4089. glClearColor(rgba[0], rgba[1], rgba[2], rgba[3]);
  4090. }
  4091. void tnsClearColor(real r, real g, real b, real a){
  4092. glClearColor(r, g, b, a);
  4093. }
  4094. //Assuming *result is long enough
  4095. void tnsMakeIndexUInt(unsigned int *result, int num, ...){
  4096. int i;
  4097. va_list list;
  4098. va_start(list, num);
  4099. for (i = 0; i < num; i++){
  4100. result[i] = va_arg(list, unsigned int);
  4101. }
  4102. va_end(list);
  4103. }
  4104. void tnsMakeTriangle(real *arr, real x1, real y1, real x2, real y2, real x3, real y3){
  4105. arr[0] = x1;
  4106. arr[1] = y1;
  4107. arr[2] = x2;
  4108. arr[3] = y2;
  4109. arr[4] = x3;
  4110. arr[5] = y3;
  4111. }
  4112. void tnsMakeQuad2d(real *arr, real x1, real y1, real x2, real y2, real x3, real y3, real x4, real y4){
  4113. arr[0] = x1;
  4114. arr[1] = y1;
  4115. arr[2] = x2;
  4116. arr[3] = y2;
  4117. arr[4] = x3;
  4118. arr[5] = y3;
  4119. arr[6] = x4;
  4120. arr[7] = y4;
  4121. }
  4122. void tnsMakeQuadT2d(real *arr, real x1, real y1, real x2, real y2, real x3, real y3, real x4, real y4){
  4123. arr[0] = x1;
  4124. arr[1] = y1;
  4125. arr[2] = x2;
  4126. arr[3] = y2;
  4127. arr[4] = x3;
  4128. arr[5] = y3;
  4129. arr[6] = x2;
  4130. arr[7] = y2;
  4131. arr[8] = x3;
  4132. arr[9] = y3;
  4133. arr[10] = x4;
  4134. arr[11] = y4;
  4135. }
  4136. void tnsMakeQuad3d(real *arr, real x1, real y1, real z1, real x2, real y2, real z2, real x3, real y3, real z3, real x4, real y4, real z4){
  4137. arr[0] = x1;
  4138. arr[1] = y1;
  4139. arr[2] = z1;
  4140. arr[3] = x2;
  4141. arr[4] = y2;
  4142. arr[5] = z2;
  4143. arr[6] = x3;
  4144. arr[7] = y3;
  4145. arr[8] = z3;
  4146. arr[9] = x4;
  4147. arr[10] = y4;
  4148. arr[11] = z4;
  4149. }
  4150. void tnsMakeQuad4d(real *arr, real x1, real y1, real z1, real w1, real x2, real y2, real z2, real w2, real x3, real y3, real z3, real w3, real x4, real y4, real z4, real w4){
  4151. arr[0] = x1;
  4152. arr[1] = y1;
  4153. arr[2] = z1;
  4154. arr[3] = w1;
  4155. arr[4] = x2;
  4156. arr[5] = y2;
  4157. arr[6] = z2;
  4158. arr[7] = w2;
  4159. arr[8] = x3;
  4160. arr[9] = y3;
  4161. arr[10] = z3;
  4162. arr[11] = w3;
  4163. arr[12] = x4;
  4164. arr[13] = y4;
  4165. arr[14] = z4;
  4166. arr[15] = w4;
  4167. }
  4168. void tnsMakeCircle2d(real *arr, int slices, real ctrX, real ctrY, real r, int jump){
  4169. int i;
  4170. real radstep = 2 * TNS_PI / (real)slices;
  4171. real rd = 0;
  4172. real x, y;
  4173. for (i = 0; i < slices; i++){
  4174. x = ctrX + cos(rd) * r;
  4175. y = ctrY + sin(rd) * r;
  4176. int idx=2 * i * (1+jump);
  4177. arr[idx] = x;
  4178. arr[idx+1] = y;
  4179. rd += radstep;
  4180. }
  4181. }
  4182. void tnsMakeArc2d(real *arr, int slices, real ctrX, real ctrY, real r, real rad_begin, real rad_end){
  4183. int i;
  4184. real radstep = (rad_end - rad_begin) / (real)slices;
  4185. real rd = rad_begin;
  4186. real x, y;
  4187. for (i = 0; i <= slices; i++){
  4188. x = ctrX + cos(rd) * r;
  4189. y = ctrY + sin(rd) * r;
  4190. arr[2 * i] = x;
  4191. arr[2 * i + 1] = y;
  4192. rd += radstep;
  4193. }
  4194. }
  4195. void tnsMakeBridgedIndex(unsigned int *result, int num, int revert, int begin){
  4196. int i;
  4197. if (!revert){
  4198. for (i = 0; i < num; i++){
  4199. result[i * 2] = begin + i;
  4200. result[i * 2 + 1] = begin + i + num;
  4201. }
  4202. }else{
  4203. for (i = 0; i < num; i++){
  4204. result[i * 2] = begin + i;
  4205. result[i * 2 + 1] = begin - i + num * 2;
  4206. }
  4207. }
  4208. }
  4209. void tnsMakeRing2d(real *arr, int *index, int slices, real ctrX, real ctrY, real r1, real r2){
  4210. tnsMakeCircle2d(arr, slices, ctrX, ctrY, r1,0);
  4211. tnsMakeCircle2d(&arr[slices*2], slices, ctrX, ctrY, r2,0);
  4212. tnsMakeBridgedIndex(index, slices, 0, 0);
  4213. index[slices*2]=0; index[slices*2+1]=slices;
  4214. }
  4215. void tnsMakeLinerGradient3d(real *arr, int num_points, real r0, real g0, real b0, real r1, real g1, real b1){
  4216. int i = 0;
  4217. real sr = (r1 - r0) / (real)num_points, sg = (g1 - g0) / (real)num_points, sb = (b1 - b0) / (real)num_points;
  4218. for (i; i < num_points; i++){
  4219. int a = 3 * i;
  4220. arr[a] = r0 + sr * i;
  4221. arr[a + 1] = g0 + sg * i;
  4222. arr[a + 2] = b0 + sb * i;
  4223. }
  4224. }
  4225. void tnsMakeLinerGradient4d(real *arr, int num_points, real r0, real g0, real b0, real a0, real r1, real g1, real b1, real a1){
  4226. int i = 0;
  4227. real sr = (r1 - r0) / (real)num_points, sg = (g1 - g0) / (real)num_points, sb = (b1 - b0) / (real)num_points, sa = (a1 - a0) / (real)num_points;
  4228. for (i; i < num_points; i++){
  4229. int a = 4 * i;
  4230. arr[a] = r0 + sr * i;
  4231. arr[a + 1] = g0 + sg * i;
  4232. arr[a + 2] = b0 + sb * i;
  4233. arr[a + 3] = a0 + sa * i;
  4234. }
  4235. }
  4236. void tnsMakeLinerGradient3dv(real *arr, int num_points, real *rgb0, real *rgb1){
  4237. int i = 0;
  4238. real sr = (rgb1[0] - rgb0[0]) / (real)num_points, sg = (rgb1[1] - rgb0[1]) / (real)num_points, sb = (rgb1[2] - rgb0[2]) / (real)num_points;
  4239. for (i; i < num_points; i++){
  4240. int a = 3 * i;
  4241. arr[a] = rgb0[0] + sr * i;
  4242. arr[a + 1] = rgb0[1] + sg * i;
  4243. arr[a + 2] = rgb0[2] + sb * i;
  4244. }
  4245. }
  4246. void tnsMakeLinerGradient4dv(real *arr, int num_points, real *rgb0, real *rgb1){
  4247. int i = 0;
  4248. real sr = (rgb1[0] - rgb0[0]) / (real)(num_points - 1), sg = (rgb1[1] - rgb0[1]) / (real)(num_points - 1), sb = (rgb1[2] - rgb0[2]) / (real)(num_points - 1), sa = (rgb1[3] - rgb0[3]) / (real)(num_points - 1);
  4249. for (i; i < num_points; i++){
  4250. int a = 4 * i;
  4251. arr[a] = rgb0[0] + sr * i;
  4252. arr[a + 1] = rgb0[1] + sg * i;
  4253. arr[a + 2] = rgb0[2] + sb * i;
  4254. arr[a + 3] = rgb0[3] + sa * i;
  4255. }
  4256. }
  4257. void tnsMakeFoucsSquare(int L, int R, int U, int B, int W){
  4258. int w = W;
  4259. //int al = Len + w;
  4260. real v[16];
  4261. //v[0] = L - w; v[1] = U - l;
  4262. //v[2] = L - w; v[3] = U + w;
  4263. //v[4] = L + l; v[4] = U + w;
  4264. //v[6] = L + l; v[7] = U - w;
  4265. //v[8] = L + w; v[9] = U - w;
  4266. //v[10] = L + w; v[11] = U - l;
  4267. //v[12] = R - l; v[13] = U + w;
  4268. //v[14] = R + w; v[15] = U + w;
  4269. //v[16] = R + w; v[17] = U - l;
  4270. //v[18] = R - w; v[19] = U - l;
  4271. //v[20] = R - w; v[21] = U - w;
  4272. //v[22] = R - l; v[23] = U - w;
  4273. tnsMakeQuad2d(v, L, U, R, U, R, B, L, B);
  4274. tnsVertexArray2d(v, 4);
  4275. tnsPackAs(GL_LINE_LOOP);
  4276. tnsMakeQuad2d(&v[8], L + W, U - W, R - W, U - W, R - W, B + W, L + W, B + W);
  4277. tnsVertexArray2d(&v[8], 4);
  4278. tnsPackAs(GL_LINE_LOOP);
  4279. }
  4280. void tnsDrawFloor(real* CamPosition, real Far, int *ShowAxis){
  4281. real OrigFar=Far;
  4282. real height=CamPosition[2];
  4283. real dist=sqrt(fabs(Far*Far-height*height));
  4284. real spanstart=Far/10000;
  4285. real spanl=1e-3,spanh=1e-3;
  4286. while((spanl*10)<spanstart){ spanl*=10; } spanh=spanl;
  4287. while((spanh*10)<Far){ spanh*=10; }
  4288. tnsFlush();
  4289. glEnable(GL_BLEND); glDepthMask(GL_FALSE); glEnable(GL_DEPTH_TEST);
  4290. tnsUseShader(T->FloorShader);
  4291. tnsEnableShaderv(T->FloorShader);
  4292. glUniform3f(T->FloorShader->uViewPos,LA_COLOR3(CamPosition));
  4293. glUniform1f(T->FloorShader->uFar,Far);
  4294. real sp=spanh;
  4295. while(sp>=spanl){
  4296. real xmin=((int)((CamPosition[0]-dist-sp)/sp))*sp,xmax=((int)((CamPosition[0]+dist+sp)/sp))*sp;
  4297. real ymin=((int)((CamPosition[1]-dist-sp)/sp))*sp,ymax=((int)((CamPosition[1]+dist+sp)/sp))*sp;
  4298. real ux=xmin; while(ux<xmax){ tnsVertex2d(ux,ymin),tnsVertex2d(ux,ymax); ux+=sp; }
  4299. real uy=ymin; while(uy<ymax){ tnsVertex2d(xmin,uy),tnsVertex2d(xmax,uy); uy+=sp; }
  4300. tnsPackAs(GL_LINES);
  4301. tnsFlush();
  4302. Far/=3; if(Far<height) break;
  4303. dist=sqrt(fabs(Far*Far-height*height)); sp/=10;
  4304. glUniform1f(T->FloorShader->uFar,Far);
  4305. }
  4306. //for (i; i < Lim; i++){
  4307. // if (i == Span && ShowAxis[0]) continue;
  4308. // tnsVertex3d(-Dist, i * Size - Dist, 0);
  4309. // tnsVertex3d(Dist, i * Size - Dist, 0);
  4310. //}
  4311. //
  4312. //for (i = 0; i < Lim; i++){
  4313. // if (i == Span && ShowAxis[1]) continue;
  4314. // tnsVertex3d(i * Size - Dist, -Dist, 0);
  4315. // tnsVertex3d(i * Size - Dist, Dist, 0);
  4316. //}
  4317. //tnsPackAs(GL_LINES);
  4318. glUniform1f(T->FloorShader->uFar,OrigFar);
  4319. if (ShowAxis[0]){ tnsColor4d(1, 0, 0, 1);
  4320. tnsVertex3d(-OrigFar, 0, 0); tnsVertex3d(OrigFar, 0, 0);
  4321. tnsPackAs(GL_LINES);
  4322. }
  4323. if (ShowAxis[1]){ tnsColor4d(0, 1, 0, 1);
  4324. tnsVertex3d(0, -OrigFar, 0); tnsVertex3d(0, OrigFar, 0);
  4325. tnsPackAs(GL_LINES);
  4326. }
  4327. if (ShowAxis[2]){ tnsColor4d(0, 0, 1, 1);
  4328. tnsVertex3d(0, 0, -OrigFar); tnsVertex3d(0, 0, OrigFar);
  4329. tnsPackAs(GL_LINES);
  4330. }
  4331. tnsFlush();
  4332. tnsUseShader(T->immShader);
  4333. tnsEnableShaderv(T->immShader);
  4334. glDepthMask(GL_TRUE);
  4335. }
  4336. void tnsDraw2DGrid10(real L, real R, real U, real B, real xmin, real xmax, real ymin, real ymax, real MostDenseW, real MostDenseH,
  4337. real* color4, real AlphaFactor, int ShowGrid, int TextAlign){
  4338. real span; real W=R-L, H=B-U, rangeX=xmax-xmin, rangeY=ymax-ymin, dW=rangeX/W, dH=rangeY/H;
  4339. real MinSpanW=fabs(MostDenseW*dW), MinSpanH=fabs(MostDenseH*dH);
  4340. for(int i=0;i<20;i++){ span=1e-5*pow(10,i); if(span>MinSpanW) break; }
  4341. real startx=((real)((int)(xmin/span)))*span; real x=startx;
  4342. while(x<xmax){
  4343. real lx=tnsInterpolate(L,R,tnsGetRatiod(xmin,xmax,x));
  4344. tnsVertex2d(lx,U);tnsVertex2d(lx,B); x+=span;
  4345. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4346. x=startx; while(x<xmax){ if((((int)round(x/span))%5)){ x+=span; continue; }
  4347. real lx=tnsInterpolate(L,R,tnsGetRatiod(xmin,xmax,x));
  4348. tnsVertex2d(lx,U);tnsVertex2d(lx,B); x+=span;
  4349. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4350. x=startx; while(x<xmax){ if((((int)round(x/span))%10)){ x+=span; continue; }
  4351. real lx=tnsInterpolate(L,R,tnsGetRatiod(xmin,xmax,x));
  4352. tnsVertex2d(lx,U);tnsVertex2d(lx,B); x+=span;
  4353. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor); tnsPackAs(GL_LINES);
  4354. for(int i=0;i<20;i++){ span=1e-5*pow(10,i); if(span>MinSpanH) break; }
  4355. real starty=((real)((int)(ymin/span)))*span; real y=starty;
  4356. while(y<ymax){
  4357. real ly=tnsInterpolate(B,U,tnsGetRatiod(ymin,ymax,y));
  4358. tnsVertex2d(L,ly);tnsVertex2d(R,ly); y+=span;
  4359. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4360. y=starty; while(y<ymax){ if((((int)round(y/span))%5)){ y+=span; continue; }
  4361. real ly=tnsInterpolate(B,U,tnsGetRatiod(ymin,ymax,y));
  4362. tnsVertex2d(L,ly);tnsVertex2d(R,ly); y+=span;
  4363. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor*AlphaFactor); tnsPackAs(GL_LINES);
  4364. y=starty; while(y<ymax){ if((((int)round(y/span))%10)){ y+=span; continue; }
  4365. real ly=tnsInterpolate(B,U,tnsGetRatiod(ymin,ymax,y));
  4366. tnsVertex2d(L,ly);tnsVertex2d(R,ly); y+=span;
  4367. } tnsColor4d(LA_COLOR3(color4),color4[3]*AlphaFactor); tnsPackAs(GL_LINES);
  4368. }