*/}}
1
0

la_tns_kernel.c 192 KB

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