*/}}
1
0

la_tns_kernel.c 190 KB

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