*/}}
1
0

la_tns_kernel.c 169 KB

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